I need to get random float values in range [-1, 1].
CGFloat max = 1;
CGFloat min = -1;
I use following code:
((float)arc4random()/RAND_MAX)*(max-min)+min
But i get value between -1.007 to 2.879 and so on. Where i have a problem. Thank you.
RAND_MAX
is not the maximum value of arc4random()
. arc4random()
returns numbers over the whole range of u_int32_t
(0 to (2^32)-1), which is a larger range than rand()
.
Also, float
is not big enough to hold all values in that range to full precision.
Try:
((double)arc4random() / UINT32_MAX) * (max - min) + min