Skip to content

Instantly share code, notes, and snippets.

Created February 13, 2014 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/8977350 to your computer and use it in GitHub Desktop.
Save anonymous/8977350 to your computer and use it in GitHub Desktop.
$ cat intgood
#!./perl6-m
sub leftrect(&f, $a, $b, $n) {
my $h = ($b - $a) / $n;
# my $sum = [+] do f($_) for $a, *+$h ... $b-$h; # gets prior def of &f somehow
my $sum = [+] (f($_) for $a, *+$h ... $b-$h); # works
$h * $sum;
}
sub tryem($f, $a, $b, $n, $exact) {
say "\n$f\n in [$a..$b] / $n";
EVAL "my &f = $f;
say ' exact result: ', $exact;
say ' rectangle method left: ', leftrect &f, $a, $b, $n;"
}
tryem '{ $_ ** 3 }', 0, 1, 100, 0.25;
tryem '{ 1 / $_ }', 1, 100, 100, log(100);
$ ./intgood
{ $_ ** 3 }
in [0..1] / 100
exact result: 0.25
rectangle method left: 0.245025
{ 1 / $_ }
in [1..100] / 100
exact result: 4.60517018598809
rectangle method left: 5.17098406528658
$ cat intbad
#!./perl6-m
sub leftrect(&f, $a, $b, $n) {
my $h = ($b - $a) / $n;
my $sum = [+] do f($_) for $a, *+$h ... $b-$h; # gets prior def of &f somehow
# my $sum = [+] (f($_) for $a, *+$h ... $b-$h); # works
$h * $sum;
}
sub tryem($f, $a, $b, $n, $exact) {
say "\n$f\n in [$a..$b] / $n";
EVAL "my &f = $f;
say ' exact result: ', $exact;
say ' rectangle method left: ', leftrect &f, $a, $b, $n;"
}
tryem '{ $_ ** 3 }', 0, 1, 100, 0.25;
tryem '{ 1 / $_ }', 1, 100, 100, log(100);
$ ./intbad
{ $_ ** 3 }
in [0..1] / 100
exact result: 0.25
rectangle method left: 0.245025
{ 1 / $_ }
in [1..100] / 100
exact result: 4.60517018598809
rectangle method left: 2378916309.88410399
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment