Okay, I wasted way too much time playing with this. First, it always bugs me when people reinvent perl's bulitins, and perl already has ranges:
sub integrate(&@) { local $x; my $sum; my $f = shift; my %o = (from => 0, by => 0.01, @_); for ($o{from} / $o{by} .. $o{to} / $o{by}) { $x = $_ * $o{by}; $sum += &$f * $o{by}; } $sum; } #> integrate { $x } from => 0, to => 1 ## 0.505
And then I thought "why not make this multidimensional?
sub integrate(&@) { my $f = shift; ## Set up some sensical defaults for ranges and vars: my ($from, $to, $by, $vars) = do { my %o = @_; for (qw(from to by vars)) { $o{$_} = [$o{$_}] if exists $o{$_} && ! ref $o{$_}; } my $dim = @{$o{from}}; $o{vars} = [qw(x y z w)[0..$dim-1]] unless $o{vars}; $o{from} = [(0) x $dim] unless $o{from}; $o{by} = [(0.01) x $dim] unless $o{by}; @o{qw(from to by vars)}; }; my $vol = 1; $vol *= $_ for @$by; ## Generate nested evaluation loops: local *intgen = sub { my ($n, $body) = @_; if ($n < 0) { '$sum += &$f * ' . $vol; } else { my ($by, $v) = ($by->[$n], $vars->[$n]); my ($lo,$hi) = ($from->[$n] / $by, $to->[$n] / $by); "for \$$v ($lo .. $hi) { \$$v *= $by ;\n" . intgen($n-1) . "\n}\n"; } }; ## Do it: (eval 'sub { my $f = shift; my $sum = 0;'.intgen($#{$from}).' $sum + }') ->($f); } #> integrate { $x * $y } from => [0,0], to => [1,1] ## 0.255025
Lightly tested, and does no error checking, but it was fun to build.

In reply to Re: Numerical integration by educated_foo
in thread Numerical integration by neniro

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.