Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Numerical integration

by educated_foo (Vicar)
on Dec 27, 2005 at 13:44 UTC ( [id://519321]=note: print w/replies, xml ) Need Help??


in reply to Numerical integration

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://519321]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2024-03-29 06:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found