Continued fraction: Difference between revisions

Content added Content deleted
m (→‎{{header|Perl 6}}: forgot to remove 'take')
(→‎{{header|Perl 6}}: on second thought it's cleaner to return functions)
Line 737: Line 737:
<lang Perl 6>sub infix:<⚬>(&f, &g) { -> $x { &f(&g($x)) } }
<lang Perl 6>sub infix:<⚬>(&f, &g) { -> $x { &f(&g($x)) } }
sub continued-fraction(@a, @b) {
sub continued-fraction(@a, @b) {
map { $_(Inf) }, [\⚬] map { @a[$_] + @b[$_] / * }, 0 .. *
[\⚬] map { @a[$_] + @b[$_] / * }, 0 .. *
}
}
printf "√2 ≈ %.9f\n", continued-fraction((1, 2 xx *), (1 xx *))[10];
printf "√2 ≈ %.9f\n", continued-fraction((1, 2 xx *), (1 xx *))[10](Inf);
printf "e ≈ %.9f\n", continued-fraction((2, 1 .. *), (1, 1 .. *))[10];
printf "e ≈ %.9f\n", continued-fraction((2, 1 .. *), (1, 1 .. *))[10](Inf);
printf "π ≈ %.9f\n", continued-fraction((3, 6 xx *), ((1, 3, 5 ... *) X** 2))[1000];</lang>
printf "π ≈ %.9f\n", continued-fraction((3, 6 xx *), ((1, 3, 5 ... *) X** 2))[1000](Inf);</lang>


The main advantage is that the definition of the function does not need to know for which rank n it is computed. This is arguably closer to the mathematical definition.
The main advantage is that the definition of the function does not need to know for which rank n it is computed. This is arguably closer to the mathematical definition.