views:

515

answers:

2

I have an interval consisting of two float numbers, and need to generate 20 random numbers in a look that are somewhere inbetween this interval defined by the two floats.

Lets say, for example:

float a = 12.49953f
float b = 39.11234f
float r = //best way to get best randomly numbers between a and b

The random number may be == a and == b. What would you suggest? I know that all computers and languages have problems with random numbers, and that there are many ways to generate them. But I have no experience in objective c.

It's pretty important that the numbers that are generated are not the same in one block of 20 numbers that are generated in the loop. I think for that I would make a method, put the number in an array and check if the generated number differs from all others in the array, and if it doesnt, I would generate another one.

I've tried this:

CGFloat r = 1 + arc4random() % 5;

but that will only generate integers, and most of the time I get 2 times the same random number after another.

+2  A: 
Tobias Langner
+4  A: 

try this

float a = 12.49953f;
float b = 39.11234f;
int startVal = a*10000;
int endVal = b*10000; 

srandom((unsigned)(mach_absolute_time() & 0xFFFFFFFF));
int randomValue = startVal+ (random() % (endVal - startVal));

float r = (float)randomValue / 10000.0f;
oxigen
try using arc4random(). I've used it and it gives pretty varied values
lostInTransit
where is the difference between srandom arc4random or random and arc4random? arc4random seems to work best.
Thanks
yes arc4random() has best result's range
oxigen