Thiele's interpolation formula: Difference between revisions

→‎{{header|Perl 6}}: modernize rho a bit
(Python solution)
(→‎{{header|Perl 6}}: modernize rho a bit)
Line 682:
 
=={{header|Perl 6}}==
{{works with|Rakudo|20102015.09-3203}}<br>
Implemented to parallel the (generalized) formula. (i.e. clearer, but naive and very slow.)
<lang perl6>use v6;
 
# reciprocal difference:
multi sub rhoρ($&f, @x where { +@x * < 1 }) { 0 } # Identity
multi sub rhoρ($&f, @x where { +@x* == 1 }) { $&f(@x[0]) }
multi sub rhoρ($&f, @x where { +@x * > 1 }) {
/ ( rho($f,@x[0] - @x[^($ord* - 1)] ) # / # ( rho[n-1](x[0], ...,- x[n-1] )
my $ord = +@x;
+/ rho($ρ(&f, @x[1..^($ord@x - 1)]); # +/ rho( ρ[n-21](x[10], ..., x[n-1])
- rhoρ($&f, @x[1..^($ord)@x]) ) # - rhoρ[n-1](x[1], ..., x[n]) )
return
+ ρ(&f, @x[0] - 1..^(@x[* - 1)] ); # + # ρ[n-2]( x[1], -..., x[n-1] )
/ ( rho($f, @x[^($ord -1)]) # / ( rho[n-1](x[0], ..., x[n-1])
- rho($f, @x[1..^($ord)]) ) # - rho[n-1](x[1], ..., x[n]) )
+ rho($f, @x[1..^($ord -1)]); # + rho[n-2](x[1], ..., x[n-1])
}
 
# Thiele:
multi sub thiele($x, %f, $ord where { $ord == +%f }) { 1 } # Identity
multi sub thiele($x, %f, $ord) {
my $&f = {%f{$^a}}; # f(x) as a table lookup
# Caveat: depends on the fact that Rakudo maintains key order within hashes
my $a = rhoρ($&f, %f.keys[^($ord +1)]);
my $b = rhoρ($&f, %f.keys[^($ord -1)]);
my $num = $x - %f.keys[$ord];
my $cont = thiele($x, %f, $ord +1);
# Thiele always takes this form:
return $a - $b + ( $num / $cont );
}
 
## Demo
sub mk-inv($&fn, $d, $lim) {
my %h;
for 0..$lim { %h{ $&fn($_ * $d) } = $_ * $d }
return %h;
}
 
sub MAIN($tblsz) {
my %invsin = mk-inv(&sin, 0.05, $tblsz);
my %invcos = mk-inv(&cos, 0.05, $tblsz);
my %invtan = mk-inv(&tan, 0.05, $tblsz);
my $sin_pi = 6 * thiele(0.5, %invsin, 0);
my $cos_pi = 3 * thiele(0.5, %invcos, 0);
my $tan_pi = 4 * thiele(1.0, %invtan, 0);
say "pi = {pi}";
say "estimations using a table of $tblsz elements:";
Line 740 ⟶ 737:
Output (table size of 6 for want of resources):
 
<pre>pi = 3.14159265358979
<pre>
pi = 3.14159265358979
estimations using a table of 6 elements:
sin interpolation: 3.1415336398551514153363985441
cos interpolation: 1.6877932165599768779321656233
tan interpolation: 3.1482623637772714826236378612</pre>
</pre>
 
=={{header|PicoLisp}}==
1,934

edits