Obj-c generate a random float(or double) number between 0 and ∏ * 2
I am trying to generate a random float(or开发者_StackOverflow社区 double) number between 0 and ∏ * 2.
All I can find is how to generate a random float number between 0 and 2.. but that leaves out .28 possibilities. (roughly)
can anyone help?
Thanks
You can make a random number between 0 and 1 and then multiply by 2pi. That should do the trick for you.
This should do it:
float f = arc4random() / ((pow(2, 32)-1)) * M_PI*2;
arc4random returns values between 0 and 2^32-1. Dividing by that number gives the range 0..1. Multiply by the range you need (2pi) gives the final range 0..2pi
Couldn't you just generate a random float between 0.0 and 1.0, then multiply it by 2PI?
精彩评论