PDA

View Full Version : Floating Point Random Numbers

ucaboys
10-06-2004, 06:51 AM
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??

Mathew Burrack
10-06-2004, 07:05 AM
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

ucaboys
10-06-2004, 09:05 AM
Thanks, I'd read of this solution on the internet. Your right since I'm only using it for testing pourposes it should suffice.