Continued fraction: Difference between revisions

→‎{{header|Perl 6}}: alternative proposal
(→‎{{header|Perl 6}}: alternative proposal)
Line 694:
e ≈ 2.718281828
π ≈ 3.141592654</pre>
 
A more original and a bit more abstract method would consist in viewing a continued fraction on rank n as a function of a variable x:
 
<math>\mathrm{FC}_4(x) = a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + x}}}</math>
 
Viewed as such, <math>\mathrm{FC}_n(x)</math> could be written recursively:
 
<math>\mathrm{FC}_n(x) = \mathrm{FC}_{n-1}(a_n + \frac{b_n}{x})</math>
 
Or in other words:
 
<math>\mathrm{FC}_n= \mathrm{FC}_{n-1}\circ f_n = \mathrm{FC}_{n-2}\circ f_{n-1}\circ f_n=\ldots=f_0\circ f_1 \ldots \circ f_n</math>
 
where <math>f_n(x) = a_n + \frac{b_n}{x}</math>
 
Perl6 allows us to define a custom composition operator. We can then use it with the reduction metaoperator, and finally we can call the resulting function with a infinite value for x.
 
<lang Perl 6>sub infix:<⚬>(&f, &g) { -> $x { &f(&g($x)) } }
sub continued-fraction(@a, @b) {
[\⚬] gather for 0 .. * { take @a[$_] + @b[$_] / * }
}
printf "√2 ≈ %.9f\n", continued-fraction((1, 2 xx *), (1 xx *))[10](Inf);
printf "e ≈ %.9f\n", continued-fraction((2, 1 .. *), (1, 1 .. *))[10](Inf);
printf "π ≈ %.9f\n", continued-fraction((3, 6 xx *), ([\+] 1, (8, 16 ... *)))[1000](Inf);</lang>
 
The ''continued-fraction'' function thus returns a lazy list of functions where the variable plays the role of the «<math>\ddots</math>» symbol in the usual representation. 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.
 
=={{header|PL/I}}==
1,934

edits