CUFP
James_H
<p>I hope this is appropriate for this section</p>
<p>Recently, I was asked to find the probability density function of distribution (pdf) of tossing 20 coins at a time. The time it took me to write a Monte Carlo simulation was half the time it took me to compute it from the binomial dist or by building a Pascal's triangle. Maybe thats not a good reflection on my math, but as you will see, I'm not a fancy Perl programmer either :)
</p>
<p>Anyway, here is the code which produces very accurate results in a matter of 30sec on my modest laptop.</p>
<p>I added mind numbing comments for utter beginners. Enjoy !</p><p>Regards, James</p>
<code># coinToss.pl
#
# Toss a collection (20 in this example) of coins a large number of times
# to determine the distribution of Heads and Tails.
# N.B. P(Head) = P(Tail) = 50% = 0.5
use strict;
# Inputs
my $numTosses = 20; # The num of coin tosses per experiment (20 in this example)
my $runs = 10000000; # 10 Million - the num of times we repeat the experiment
# Program vars
my $i; # a looping variable
my $j; # another looping var
my $toss; # Keeps running total of the number of 'Heads' during current experiment
my @collect; # An array that keeps a total of the number of 'Heads' counted
# in all previous experiment.
my $percent; # To convert $collect[0] - $collect[19] to %
# Outer loop: Repeat "$runs" times
for ($j = 0; $j < $runs; $j++) {
# Inner loop: One run of 20 tosses
for ($i = 0; $i < $numTosses; $i++) {
$toss += (rand() < 0.5) ? 1 : 0;
#print "$toss\n";
}
$collect[$toss]++;
$toss = 0;
}
# Print results
print "\nTails\tCount out of $runs\t%\n";
for ($i = 0; $i < $numTosses+1; $i++) {
$percent = sprintf "%.2f", $collect[$i] / $runs * 100;
print "$i\t$collect[$i]\t\t\t$percent%\n"
}</code>