Some of the coolest programs are the ones with random results... russian roullette, initial placement in Life, etc.

I wanted to see how close to even rand() would get over a large sample size, so I ran 100 million tests, and published the results.

If this gets moved to Code Catacombs, that's fine by me. It's not exactly cool, but it is cool by extension. :)

Also, if someone would like to comment on how it could be made more efficient, that would be awesome! I'm specifically interested in the while block, because it's the workhorse, though other comments are good too.

Code:

#!/usr/bin/perl -w use strict; my ($counter, $tests) = (0, 100_000_000); my %results; my $rand; #declare once, save time while ($counter++ < $tests) { #not creating with .. operator, m +em efficient $rand = int(rand(10) + 1); $results{$rand}++; } my $total; $total += $_ for values %results; #only 10 results possible print "\n\n"; print "Total\t$total\n\n"; print "$_:\t$results{$_}\t\t" . $results{$_} / $total * 100 . "\n" for sort {$a <=> $b} keys %results; print "\n\n";

Output:

Total   100000000
 
1:      10003440                10.00344
2:      9996091         9.996091
3:      10004370                10.00437
4:      9996926         9.996926
5:      10000607                10.000607
6:      9998471         9.998471
7:      10002412                10.002412
8:      9997738         9.997738
9:      9999782         9.999782
10:     10000163                10.000163

In reply to Lots of rand()s by David Caughell

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.