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":



  • 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.