If you didn't want to use the smarter Math::Integral::Romberg and you are rolling your own, then it makes a lot of sense to use Simpson's method instead. Almost as little work, and you actually take into account the second derivative information, and make the third derivative irrelevant by a nice piece of symmetry.
# Takes a function, start point, end point, and number of intervals. # Returns a numerical approximation of the integral using Simpsons Rul +e. sub integrate_simpson { my ($func, $start, $end, $n) = @_; my $width = ($end - $start)/$n; my $mid_sum = sum(map {$func->($start + ($_ - 0.5)*$width)} 1..$n); my $int_sum = sum(map {$func->($start + $_ *$width)} 1..$n-1); my $first = $func->($start); my $last = $func->($end); ($first + $last + 4*$mid_sum + 2*$int_sum) * $width / 6; } sub sum { my $sum = shift; $sum += shift while @_; return $sum; } # And to test print integrate_simpson(sub {$_[0]**3}, 0, 1, 9)

In reply to Re (tilly) 2: Simple Integration using Perl by tilly
in thread Simple Integration using Perl by Anonymous Monk

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.