Floating Point Random Numbers

Hi, I´m making a 3D Satellite tracking system as hobbie, I wan´t to test out my application by initializing my satellites with randon numbres, but I can´t fin a function that return random values between 0 & 1.0, or in its defect a function that complies with “int random(x)” where the return is between 0 & X. Can anyone help??

float randFloat( float x )
{
   return (float)rand() * x / (float)RAND_MAX;
}

That should work, although I think you’ll have to include math.h at the top. Nothing Mac-specific about it. If there’s a real floating-point random function though, I don’t know of it.

Note that RAND_MAX usually is either 32,767 or 65,535, so if you give a big x to the function, you’re not going to end up with very random numbers. Instead, you could try something like the following:

float randFloat2( float x )
{
    return (float)rand() * x / (float)RAND_MAX + (float)rand() / (float)RAND_MAX;
}

(so long as x is not less than 1, at least, since the second term will return a number [0…1].)

Alternatively, if you want really good random numbers, rand() isn’t the best solution. Try googling for gaussian random algorithms or the like and you should find some good functions for generating random numbers from scratch, probably including floating point ones. For just something quick and dirty, though, either of the above should suffice.

-mcn

Thanks, I’d read of this solution on the internet. Your right since I’m only using it for testing pourposes it should suffice.

the low bits of rand() aren’t very random, but the high bits are pretty good. When you do as suggested here, the high bits are most significant, so this should be decently random.

On Mac OS X, RAND_MAX is 2^31-1 or something large like that… don’t know where you got the smaller numbers from.

Originally posted by OneSadCookie:
On Mac OS X, RAND_MAX is 2^31-1 or something large like that… don’t know where you got the smaller numbers from.
Ancient technology :slight_smile: Back in the day when I checked, it was the positive limit of a signed 16-bit integer. I haven’t ever bothered to check on modern systems, since I just always use the #define. I had kinda assumed the 16-bit random number was a C convention, but clearly I was wrong. Nice to know :slight_smile:

–mcn

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.