in reply to Probability sum of random variables

This should easily do large sums of many random variables. The technique to do large convolutions is called http://en.wikipedia.org/wiki/Exponentiation_by_squaring.

BTW P-value has a different meaning. You really just want to call it probability.

Enjoy!

#!/usr/bin/perl -w use strict; #Set no. of elements, frequencies and the sum value my @freq = qw (0.1 0.2 0.7); my $nElements = 2; my $targetSum = 4; # # If you are only interested in the first few $targetSums # and @freq is a large array, you can speed up the computation # and reduce space requirements by setting $maxSum to the # largest conceivable $targetSum # my $maxSum=400; sub conv { my ($p, $q) = @_; my ($np, $nq) = (scalar @$p, scalar @$q); my @ans = (); push @ans, 0 for (1..$np+$nq); my $ip = 0; for my $vp (@$p) { my $iq = 0; for my $vq (@$q) { $ans[$ip+$iq] += $vp*$vq; $iq++; last if $ip+$iq > $maxSum; } $ip++; } return \@ans; } # see http://en.wikipedia.org/wiki/Exponentiation_by_squaring sub convn { my ($n, $p) = @_; my $ans = [1]; while ($n) { $ans = conv($ans, $p) if $n & 1; # if n is odd $p = conv($p, $p); use integer; $n = $n >> 1; } return $ans; } my $ans = convn($nElements, \@freq); print "Prob(sum of $nElements = $targetSum) = $ans->[$targetSum]\n"; #Prints: Prob(sum of 2 = 4) = 0.49 print convn(200, [0.1, 0.2, 0.3, 0.2, 0.1, 0.1])->[400]; #Prints: 0.000210606620621573

Replies are listed 'Best First'.
Re^2: Probability sum of random variables
by FFRANK (Beadle) on Sep 04, 2007 at 00:57 UTC
    Hi b4,

    Your solution is great and fast, Thanks very much !

    FFRANK