Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random number generation between two floats

I am trying to generate a random number between two floats (the max is increased by its half)

this is what I have so far but it's not working

    //range
    NSString *minString = [dict objectForKey:@"min"];
    float minRange = [minString floatValue];
    NSString *maxString = [dict objectForKey:@"max"];
    float maxRange = [maxString floatValue];

    NSLog(@"the ORIGINAL range is %f - %f", minRange, maxRange);

    maxRange = maxRange + (maxRange/2);

    //If you want to get a random integer in the range x to y, you can do that by int randomNumber = (arc4random() % y) + x;

    float randomNumber = (arc4random() % maxRange) + minRange; //ERROR: "Invalid operands to binary expression ('float' and 'float')

    NSLog(@"the range is %f - %f", minRange, maxRange);
    NSLog(@"the random number is %f", randomNumber);
like image 223
BlockReader Avatar asked Jun 30 '11 01:06

BlockReader


People also ask

How do you generate a random float number?

In order to generate Random float type numbers in Java, we use the nextFloat() method of the java. util. Random class. This returns the next random float value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence.

How do you generate random float numbers between specific ranges in C++?

float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX); This will generate a number from 0.0 to some arbitrary float , X : float r2 = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX/X));

How do you get a random float between 0 and 1 in Python?

uniform() function. The random. uniform() function is perfectly suited to generate a random number between the numbers 0 and 1, as it is utilized to return a random floating-point number between two given numbers specified as the parameters for the function.


1 Answers

Include:

#define ARC4RANDOM_MAX 0x100000000

And then try this:

double val = ((double)arc4random() / ARC4RANDOM_MAX) 
   * (maxRange - minRange)
   + minRange;
like image 177
Richard Schneider Avatar answered Oct 09 '22 07:10

Richard Schneider