Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a random float in Objective-C?

I'm trying to create a random float between 0.15 and 0.3 in Objective-C. The following code always returns 1:

int randn = (random() % 15)+15;
float pscale = (float)randn / 100;

What am I doing wrong?

like image 698
Roman Avatar asked Aug 04 '10 21:08

Roman


5 Answers

Here is a function

- (float)randomFloatBetween:(float)smallNumber and:(float)bigNumber {
    float diff = bigNumber - smallNumber;
    return (((float) (arc4random() % ((unsigned)RAND_MAX + 1)) / RAND_MAX) * diff) + smallNumber;
}
like image 164
Boris Avatar answered Oct 18 '22 13:10

Boris


Try this:

 (float)rand() / RAND_MAX

Or to get one between 0 and 5:

 float randomNum = ((float)rand() / RAND_MAX) * 5;

Several ways to do the same thing.

like image 30
Caladain Avatar answered Oct 18 '22 13:10

Caladain


  1. use arc4random() or seed your random values
  2. try

    float pscale = ((float)randn) / 100.0f;
    
like image 4
Lou Franco Avatar answered Oct 18 '22 12:10

Lou Franco


Your code works for me, it produces a random number between 0.15 and 0.3 (provided I seed with srandom()). Have you called srandom() before the first call to random()? You will need to provide srandom() with some entropic value (a lot of people just use srandom(time(NULL))).

For more serious random number generation, have a look into arc4random, which is used for cryptographic purposes. This random number function also returns an integer type, so you will still need to cast the result to a floating point type.

like image 3
dreamlax Avatar answered Oct 18 '22 11:10

dreamlax


Easiest.

+ (float)randomNumberBetween:(float)min maxNumber:(float)max
{
    return min + arc4random_uniform(max - min + 1);
}
like image 2
jose920405 Avatar answered Oct 18 '22 12:10

jose920405