Real Random - KISS
CassLan
Posts: 586
I understand this generates a long...but what if I want a random number between··0 and 24?
I was doing (rr.random//24) but I'm not sure this is the way to do this.
Thanks
Rick
I was doing (rr.random//24) but I'm not sure this is the way to do this.
Thanks
Rick
Comments
Leon
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Amateur radio callsign: G1HSM
Suzuki SV1000S motorcycle
Post Edited (Leon) : 6/27/2008 3:34:14 AM GMT
x := (rr.random/2^32) * 39
With the code above, I'm trying to get a number between 0-39, instead I get 0-240 so far.
This is because the // operator, when the divisor is not a power of 2, will give slightly skewed results. However, if nearly perfect statistics are unimportant, the modulo operator — especially for small ranges — is probably good enough.
-Phil
Addendum: Here's a method that should yield results quicker than the above:
This has the same statistics as the first example but throws away far fewer results. Due to the two divisions and one muliplication, though, its advantages diminish as the high end of the range approaches a powwer of two.
-P.
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
'Still some PropSTICK Kit bare PCBs left!
Post Edited (Phil Pilgrim (PhiPi)) : 6/27/2008 4:21:04 AM GMT
You need to use floating point. I should have said multiply by 25 and subtract 1, so you could try mutiplying by 40 and subtracting 1.
This is the standard technique used with the usual random number functions like that provided with gcc, that generate a number between 0 and 1. It gives a proper uniform random distribution and doesn't 'waste' any numbers.
Leon
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Amateur radio callsign: G1HSM
Suzuki SV1000S motorcycle
Post Edited (Leon) : 6/27/2008 4:33:14 AM GMT