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
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;
How about something like:
Code:float R = (float)((rand()%100)/10)
That kept giving me whole numbers for some reason. I don't get it, ten doesn't evenly divide into all numbers.
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
Only way I can think of is to seed rand to a float. Try this:
this seemed to work for me. If you only divide by a tenth, it gives an int...play around with it.Code:srand(.5);
float R = (float)((rand()%100)/.55);
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:
If you're wondering what the "+0.1" is for at the end, after some testing, I found this makes it more random. Before it would just randomize to 2 decimal places, this lets itself max out the decimal places.Code:inline float FloatRand(float MaxVal)
{
return float(rand()%100)/((100/MaxVal)+0.1);
}
Code:float FloatRand( float MaxVal )
{
return ( (float)rand( ) / (float)RAND_MAX ) * MaxVal;
}
This is indeed the best way.Quote:
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).
Code:float FloatRand( float MaxVal )
{
return ( (float)rand( ) / ( (float)RAND_MAX + 1.0f ) ) * MaxVal;
}