Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most optimal way to get a random floatingpoint number between floatA and floatB?

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.

like image 439
Thanks Avatar asked May 20 '09 10:05

Thanks


People also ask

How do you generate a random floating-point number?

Use a random. random() function of a random module to generate a random float number uniformly in the semi-open range [0.0, 1.0) . Note: A random() function can only provide float numbers between 0.1. to 1.0. Us uniform() method to generate a random float number between any two numbers.

Which function is used to generate floating-point random numbers?

We can generate float random numbers by casting the return value of the rand () function to 'float'. Thus the following will generate a random number between float 0.0 and 1.0 (both inclusive).

What is random float?

random-float is a mathematics primitive that reports a random floating point number anywhere between 0 and the given number. For instance, random-float 10 could report 6.9105, 7, 4.2, 0.451, 0.0000001, 9.99999, etc. random-float is very useful in modeling phenomena that require continuous numbers.


1 Answers

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; 
like image 125
oxigen Avatar answered Nov 14 '22 23:11

oxigen