Howdy!

#!/usr/bin/perl use strict; use warnings; sub P { my @r = @_; my $n = $#r; return $r[1] if $n == 1; # inferred end to recursion my $sum = 0; for my $i (1..$n) { my @r_prime = @r; splice(@r_prime, $n-$i+1, 1); $sum += ($r[$n-$i+1] - $r[$n-$i]) * P(@r_prime); } return $sum; } while (<DATA>) { chomp; my @r = split(/,/, $_); unshift @r, 0; # sets r-naught print "P($_) = ", P(@r), "\n"; } __DATA__ 0.11, 0.07, 0.19 0.43, 0.31, 0.37 0.93, 0.78, 0.82 0.91, 0.12, 0.15 0.52, 0.18, 0.32
gave the following output:
P(0.11, 0.07, 0.19) = 0.001595 P(0.43, 0.31, 0.37) = 0.046225 P(0.93, 0.78, 0.82) = 0.548235 P(0.91, 0.12, 0.15) = 0.439894 P(0.52, 0.18, 0.32) = 0.010192

The expansion looks similar to computing a determinant, but not quite...this is a straight-up translation of the formula into Perl. No trickery; no premature optimization.

Update:

I elected to prepend a zero to the array of r values to simplify life. That also means that the indices in the formula now correspond to the array indices in the Perl code, making the Perl read more nearly like the formula. I elected to construct the array for the recursion explicitly, by directly striking the omitted r value.

This is meant to make it easier to audit the code to verify that it says what it is meant to say...

yours,
Michael

In reply to Re: recursive formula. by herveus
in thread recursive formula. by BioGeek

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":