A few minutes ago, ferrency asked in the chatterbox what the odds were of "winning" (getting the most "heads", for example) if one player flips a fair coin M times while another player flips a coin N times. ferrency was hoping for a closed form solution (one that doesn't require iterating).
I didn't come up with a closed form, but I did come up with a solution that is pretty efficient when doing the computation for lots of values of N and M.
I was rather surprised that it appears to have worked on the first try so I'm a bit suspicious that I have one or two off-by-one errors in the code. Though, the results appear correct and the self test in the code passes, so perhaps I just got lucky. (:
#!/usr/bin/perl -w use strict; use mapcar; main( @ARGV ); exit( 0 ); BEGIN { my @freq; my $max= 0; my @f= (0,1,2); sub freq { my( $n )= @_; while( @freq < $n ) { push @freq, [@f]; @f= mapcar { $_[0]+$_[1] } [@f,$f[-1]], [0,@f]; } return $freq[$n-1]; } } sub odds { my( $m, $n )= @_; ( $m, $n )= ( $n, $m ) if $n < $m; my @Fm= @{ freq($m) }; my @Fn= @{ freq($n) }; my( $win, $lose, $draw )= ( 0, 0, 0 ); for my $i ( 0..$m ) { my $f= $Fm[$i+1] - $Fm[$i]; $win += $f * $Fn[$i]; $draw += $f * ($Fn[$i+1]-$Fn[$i]); $lose += $f * ($Fn[-1]-$Fn[$i+1]); } $lose += $Fm[-1] * ( $Fn[-1] - $Fn[$n+1] ); my $tot= $win + $draw + $lose; die "Broken" if $tot != $Fm[-1]*$Fn[-1]; return $win/$tot, $draw/$tot, $lose/$tot; } sub main { die "Usage: $0 max\n" unless 1 == @ARGV; my( $max )= @_; for my $n ( 1..$max ) { for my $m ( 1..$n ) { my $line= sprintf "%2d,%2d: %19.17f %19.17f %19.17f\n", $m,$n,odds($m,$n); $line =~ s#(?<=\d)(0+ )# " " x length($1) #ge; $line =~ s#(?<=\d)0+$##; print $line; } print $/; } }
This requires mapcar.
The first block defines a function that, given a count of coin tosses, returns a reference to an array where $ref->[$i+1] is the number of ways you can get $i or fewer "heads" (and where 0 == $ref->[0] for convenience). So 1 == $ref->[1] and 2**$N == $ref->[-1].
odds($m,$n) returns the odds of a win/draw/lose for players tossing $m and $n times. The main block displays the results for all combinations upto the maximum you give on the command line.
- tye (but my friends call me "Tye")
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Odds between two players flipping a coin M and N times
by ferrency (Deacon) on May 15, 2002 at 16:44 UTC | |
|
(tye)Re: Odds between two players flipping a coin M and N times
by tye (Sage) on May 15, 2002 at 16:32 UTC | |
|
Re: Odds between two players flipping a coin M and N times
by kvale (Monsignor) on May 15, 2002 at 23:25 UTC |