Numerical integration: Difference between revisions

Content added Content deleted
m (→‎{{header|FreeBASIC}}: added some info)
Line 3,199:
=={{header|Perl 6}}==
 
{{works with|Rakudo|2010.2015-09.12-24}}
 
<lang perl6>sub leftrect(&f, $a, $b, $n) {
my $h = ($b - $a) / $n;
$h * [+] do f($_) for $a, *$a+$h ... $b-$h;
}
sub rightrect(&f, $a, $b, $n) {
my $h = ($b - $a) / $n;
$h * [+] do f($_) for $a+$h, *$a+$h+$h ... $b;
}
sub midrect(&f, $a, $b, $n) {
my $h = ($b - $a) / $n;
$h * [+] do f($_) for $a+$h/2, *$a+$h+$h/2 ... $b-$h/2;
}
sub trapez(&f, $a, $b, $n) {
my $h = ($b - $a) / $n;
$h / 2 * [+] f($a), f($b), |do f($_) * 2 for $a+$h, *$a+$h+$h ... $b-$h;
}
Line 3,236:
sub tryem($f, $a, $b, $n, $exact) {
say "\n$f\n in [$a..$b] / $n";
evalEVAL "my &f = $f;
say ' exact result: ', $exact;
say ' rectangle method left: ', leftrect &f, $a, $b, $n;
Line 3,244:
say ' quadratic simpsons rule: ', simpsons &f, $a, $b, $n;"
}
 
tryem '{ $_ ** 3 }', 0, 1, 100, 0.25;
 
tryem '1 / *', 1, 100, 1000, log(100);
 
tryem '{$_}*.self', 0, 5_000, 10_0005_000_000, 12_500_000;
 
tryem '{$_}*.self', 0, 6_000, 12_0006_000_000, 18_000_000;</lang>
{{out}}
(We run the last two tests with fewer iterations to avoid burning 60 hours of CPU,
since rakudo hasn't been optimized yet.)
 
Output:
<lang>{ $_ ** 3 }
in [0..1] / 100
Line 3,261 ⟶ 3,258:
rectangle method left: 0.245025
rectangle method right: 0.255025
rectangle method mid: 0.2499875249988
composite trapezoidal rule: 0.250025
quadratic simpsons rule: 0.25
Line 3,274 ⟶ 3,271:
quadratic simpsons rule: 4.60517038495714
 
*.self
{$_}
in [0..5000] / 100005000000
exact result: 12500000
rectangle method left: 1249875012499997.5
rectangle method right: 1250125012500002.5
rectangle method mid: 12500000
composite trapezoidal rule: 12500000
quadratic simpsons rule: 12500000
 
*.self
{$_}
in [0..6000] / 120006000000
exact result: 18000000
rectangle method left: 1799850017999997
rectangle method right: 1800150018000003
rectangle method mid: 18000000
composite trapezoidal rule: 18000000
quadratic simpsons rule: 18000000</lang>
 
Note that these integrations are done with rationals rather than floats, so should be fairly precise (though of course with so few iterations they are not terribly accurate (except when they are)). Some of the sums do overflow into Num (floating point)--currently rakudo allows implements64-bit Rat32denominators--but at least all of the interval arithmetic is exact.
 
=={{header|PL/I}}==