in reply to Simple Integration using Perl

Since a symbolic approach has been clearly shot down, I thought I'd suggest using the trapezoidal rule. Divide your interval into n even parts. Calculate the value of the function for each point that marks a boundary between parts of your interval. Use the values of these points to construct a series of trapezoids, bounded on the bottom with the x-axis. Then find the sum of the areas of the trapezoids.

A better approximation can be found by splitting the interval into uneven parts, basing your decision on the second derivative of the function. That is, you want to have more divisions in areas where the slope of the function changes a lot, and fewer divisions where the slope remains stable. The actual algorithm to implement this is left as an exercise for the reader. It's probably cheaper to just add more n when using the above approach, than to try and calculate all those derivatives, anyway.

Update: dragonchild- When you're holding a hammer, everything looks like a nail.


TGI says moo

Replies are listed 'Best First'.
Re (tilly) 2: Simple Integration using Perl
by tilly (Archbishop) on Jan 29, 2002 at 02:13 UTC
    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)
Re: Re: Simple Integration using Perl
by dragonchild (Archbishop) on Jan 29, 2002 at 00:57 UTC
    Of course, the very fact that one is thinking about doing heavy computational activities within Perl instead of (correctly) farming it out to a computational language like C or FORTRAN should be a tip-off that one has the wrong tool for the right job.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.