Getting wrong return on Rand()
BlitzMax Forums/BlitzMax Programming/Getting wrong return on Rand()
| ||
Something's up with the Rand function. I'm trying to get a random number from -1 to 1 and it's only returning 0s and 1s. Try this:For a=1 to 1000 Print Rand(-1,1) Next In order to get -1s I'm having to do Rand(-2,1) which is throwing off my probabilities (which I don't want). |
| ||
You're saying integers between -1 and 1 which is 0 and 1. To include -1 you need rand(-2,1) <Edit> Why is it throwing off your probabilities? <edit> In fact, this might be caused by the 'double' precision issue. |
| ||
Rand() is for integers. |
| ||
but uses doubles. |
| ||
Do you want a random float? If so try RndFloat() which returns a number from 0.0 to 1.0 |
| ||
Because RAND returns a double but the function is declared to return an int, values such as -0.98 are set to 0. It is possible to get -1 returned but not 1/3 of the time. Setting rand(-2,1) will return values such as -1.9 set to -1. <edit> B3D doesn't have this problem. |
| ||
Matt...Rnd() is for floats. I'm looking for an integer hence I'm using Rand(). When I say throwing off my probabilities I mean I'll get 0 more than -1 or 1. As you said there's not an even 1/3 chance to get each number by using Rand(-2,1) because anything in the -1 range is coming up a zero. It would actually be 1 1/4 of the time, 0 1/2 of the time, and -1 1/4 of the time. Hope this gets fixed soon. |
| ||
What numbers will you be dealing with? Could you create your own function which adds 100 to min/max? Function small_rand:Int(Minvalue,maxvalue) startvalue=minvalue+100 endvalue=maxvalue+100 mynum=Rand(startvalue,endvalue) Return mynum-100 End Function For x = 1 To 100 Print small_rand(-1,1) Next ? |
| ||
For a=1 To 1000 DebugLog Rand(0,2)-1 Next |
| ||
The Rand(0,2) - 1 trick is good enough for this particular problem. The trouble is that Rand() should round down, i.e. toward -Infinity. It actually rounds toward zero, which is how BlitzMax converts floating point values to integer. Here is an alternate version of Rand() which uses Floor() to enforce the correct rounding. I haven't seriously tested this, but it seems like it should work. Function Rand2( min_value,max_value=1 ) Local delta!=Double(max_value)-Double(min_value) If delta>0 Return Floor( RndDouble()*(1+delta) ) + min_value Return Floor ( RndDouble()*(1-delta) ) + max_value End Function |
| ||
Beaker for the win! |
| ||
Hope this gets fixed soon. Me too! |