PDA

View Full Version : Random float ?



McZ
10-15-2001, 03:19 AM
how to make a random float between -1.0f and 1.0f or something like that?

Bob
10-15-2001, 03:25 AM
float randomNumber = (2.0 * float(rand()) / float(RAND_MAX)) - 1.0;

Or something like that.

marcus256
10-16-2001, 10:25 PM
Originally posted by McZ:
how to make a random float between -1.0f and 1.0f or something like that?

This is an old code that I have used (if you do not want to rely on rand()). It works very well:

double myrand( void )
{
static unsigned long seed = 123;
seed = (1103515245L * seed + 12345L ) & 0x7fffffffL;
return 1.0 - ((double)seed/(double)0x3fffffff);
}

Of course, you can expand it to use a configurable seed etc...

/Marcus