http://qs321.pair.com?node_id=441728

monkfan has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
I am attempting to compute a binomial distribution based on formulation here.

Basically binomial distributions return the probability of an event occuring $k times. In $n attempts, where the probability of it occuring in a single attempt is $p.

I tried two methods that should give the identical result. One subroutine using Math::Pari via its 'binomial' function plus logarithmic function and the other one using brute combinatorial method. In the end it's the log-Math::Pari method which I intended to use, since it is able to handle large number.

But however the result given by log-Math::Pari function is different from the correct combinatorial Method.
Sub Binom Comb = 0.3125 #This is correct Sub Binom Log = 0.06868298952623189587 #wrong
What's wrong with my log-Math::Pari subroutine? It seems to me I have constructed log version mathematically in a right way. Or have I used the Math::Pari function wrongly?
#!/usr/bin/perl -w use strict; use Math::Pari qw(binomial); my $n = 6; my $k = 3; my $p = 0.5; my $sub_binom_comb = binomial_comb($k,$n,$p); my $sub_binom_log = binomial_log($k,$n,$p); print "Sub Binom Comb = $sub_binom_comb\n"; print "Sub Binom Log = $sub_binom_log\n"; #----My Subroutines ------------ sub binomial_log{ #Find binomial distributions using Log #and Math::Pari my ($k, $n, $p) = @_; my $first = log(binomial($n,$k)); #The above binomial function from Math::Pari my $second = $k * log($p); my $third = ($n-$k) * log (1-$p); my $log_Prob = $first + $second + $third; my $Prob = 10 ** ($log_Prob); return $Prob; } sub binomial_comb { #With combinatorial method #using brute factorial my ($x, $n, $p) = @_; return unless $x >= 0 && $x == int $x && $n > 0 && $n == int $n && $p > 0 && $p <1; return choose($n,$k) * ($p ** $x) * ((1-$p) ** ($n-$x)); } sub choose { my ($n,$k) = @_; my ($result,$j) = (1,1); return 0 if $k>$n||$k<0; $k = ($n - $k) if ($n - $k) <$k; while ($j <= $k ) { $result *= $n--; $result /= $j++; } return $result; }
Regards,
Edward