How do I do rand() for floats? Obviously this won't work:

So how do I do it?Code:`float a = (float)rand() % 5.2;`

Printable View

- 11-24-2003frenchfry164rand() for floats
How do I do rand() for floats? Obviously this won't work:

Code:`float a = (float)rand() % 5.2;`

- 11-24-2003JaWiB
How about something like:

Code:`float R = (float)((rand()%100)/10)`

- 11-24-2003frenchfry164
That kept giving me whole numbers for some reason. I don't get it, ten doesn't evenly divide into all numbers.

- 11-24-2003JaWiB
D'oh! Should've been:

Code:`float R = float(rand()%1000) / 100 ;`

Or actually probably should've used a C++ cast...but anyways...

Edit: I should mention that someone else probably knows a better way, but at least this works :D - 11-24-2003axon
Only way I can think of is to seed rand to a float. Try this:

Code:`srand(.5);`

float R = (float)((rand()%100)/.55);

- 11-24-2003frenchfry164
thx dude!

*gives a straight huggle

*wait a minute, I'm a guy......saying huggle? Man, I got issues.

edit: Okay! I got this worked out! You don't even need to seed with a float, just seed it with time as normal. Here is my function:

Code:`inline float FloatRand(float MaxVal)`

{

return float(rand()%100)/((100/MaxVal)+0.1);

}

- 11-24-2003XSquaredCode:
`float FloatRand( float MaxVal )`

{

return ( (float)rand( ) / (float)RAND_MAX ) * MaxVal;

}

- 11-25-2003CatQuote:

*Originally posted by XSquared*

Code:`float FloatRand( float MaxVal )`

{

return ( (float)rand( ) / (float)RAND_MAX ) * MaxVal;

}

Do note that this can SOMETIMES return MaxVal; so the range of numbers is [0,MaxVal] -- it includes BOTH endpoints. If this is not what you want, you need to check for that condition.

I mention this because often you want a number, for example, in the range [0,1) -- and a value of exactly 1 might break everything, once every RAND_MAX times you call the function. Very difficult to debug. In this case, you could use something like:

Code:`float r;`

while ( (r = FloatRand(1)) == 1);

// now r is in the range [0,1).

- 11-25-2003XSquaredCode:
`float FloatRand( float MaxVal )`

{

return ( (float)rand( ) / ( (float)RAND_MAX + 1.0f ) ) * MaxVal;

}