# Thread: Floating Point Random Numbers

1. ## 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??

2. ## Re: Floating Point Random Numbers

Code :
```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:

Code :
```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

3. ## Re: Floating Point Random Numbers

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

4. ## Re: Floating Point Random Numbers

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.