views:

172

answers:

3

Hi,

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?

+2  A: 

Try this:

 (float) random()/RAND_MAX

Or to get one between 0 and 5:

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

Several ways to do the same thing.

Caladain
This is wrong. `random() / RAND_MAX` will not give you a floating-point value as neither value is floating-point. Also, the domain of `random()` is not 0 to RAND_MAX. The domain of `rand()` and `rand_r()` is. So you should use: `(float)rand() / RAND_MAX` to get the expected result.
Jonathan Grynspan
A: 
  1. use arc4random() or seed your random values
  2. try

    float pscale = ((float)randn) / 100.0f;
    
Lou Franco
A: 

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.

dreamlax