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

In reply to Re: Probability sum of random variables by b4swine
in thread Probability sum of random variables by FFRANK

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.