Numbered Steps to Reproduce Problem:
- Call rand(x,y) a large amount of times (~50M) in a loop
- Watch the return value occasionally be y+1
Code Snippet (if applicable) to Reproduce Problem:
/world/New()
var/list/count[6]
for(var/k = 1 to 10)
for(var/i = 1 to 5000000)
count[rand(1,5)]++
// count[round(rand()*5 + 1)]++
for(var/i = 1 to count.len)
world.log << "[i]=[count[i]]"
(swap the commented-out line with the one above it for how I'm guessing rand(x,y) is implemented internally - it shows identical behaviour)
Example output:
1=1.00025e+07
2=1.00027e+07
3=9.99989e+06
4=9.99671e+06
5=9.99818e+06
6=3
Expected Results: rand(x,y) would return an integer between x and y inclusive with roughly equal probability, as specified by the reference
Actual Results: rand(x,y) very occasionally returns y+1
Does the problem occur:
Every time? Or how often? Less than once per ten million calls (when rand() returns 1.0)
In other games? N/A
In other user accounts? Unknown
On other computers? Unknown
Did the problem NOT occur in any earlier versions? If so, what was the last version that worked? Unknown
Workarounds: Check the return from rand(x,y)?
Interestingly, your numbers coincide exactly with my hunch. The problem comes in because the raw rand() is a 32-bit number divided by 2^32, which works fine for double precision, but for floating point it will round. ANDing the number with 0xFFFFFF00 before the division will solve the problem.