Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^2: Perl rand() generates larger numbers for small sample size, bug!

by Bethany (Scribe)
on Aug 08, 2014 at 02:23 UTC ( [id://1096707]=note: print w/replies, xml ) Need Help??


in reply to Re: Perl rand() generates larger numbers for small sample size, bug!
in thread Perl rand() generates larger numbers for small sample size, bug!

"rand()" is not cryptographically secure. You should not rely on it in security-sensitive situations.

True, but if it really behaved as the OP said it does it wouldn't even be useful for dice games.

The bug exists but it's in the OP's testing script, not in rand(). $sum keeps accumulating more and more numbers, then being divided by 7. The first time through the sum of 7 randoms gets divided by 7. So far so good. But the second time through the sum of 14 randoms (the first seven plus seven more) gets divided by 7. The third time, the sum of 21 randoms gets divided by 7, and so forth.

ETA: The above paragraph is buggy too! I should say the second time, you're adding the sum of 7 more randoms plus 1/7 of the sum of the first 7. The third time you have seven more, plus 1/7 the sum of the second 7, plus 1/49 the sum of the first 7, and so forth. That's why the discrepancy is greater with a small "sample size" — the denominator of the fraction is small, dividing by it results in a larger quotient. It's also why increasing the number of times the outer loop runs produces an asymptotic effect; the more you increase it, the less effect further increases have on the discrepancy from 0.5 because each loop's arithmetic error gets divided out by the (one-less-than-the-number-of-outer-loops-so-far)th power of 7, meaning early errors practically vanish.

The fix is easy. Clear $sum to zero at the beginning of each outer loop and voila — results are right around 0.5 where they ought to be. I tried the code before posting to be sure and yup, it works.

  • Comment on Re^2: Perl rand() generates larger numbers for small sample size, bug!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1096707]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2024-04-20 01:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found