Continued fraction: Difference between revisions

Content deleted Content added
Grondilu (talk | contribs)
m →‎{{header|Perl}}: vertical alignment
Grondilu (talk | contribs)
→‎{{header|Perl 6}}: not returning functions: evaluating to Inf inside the main function
Line 713: Line 713:
where <math>f_n(x) = a_n + \frac{b_n}{x}</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 triangular reduction metaoperator, and finally we can call the resulting function with a infinite value for x (any value would do actually, but infinite make it consistent with this particular task).
Perl6 allows us to define a custom composition operator. We can then use it with the triangular reduction metaoperator, and map each resulting function with an infinite value for x (any value would do actually, but infinite make it consistent with this particular task).


<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) {
[\⚬] gather for 0 .. * { take @a[$_] + @b[$_] / * }
map { $_(Inf) }, [\⚬] gather for 0 .. * { take @a[$_] + @b[$_] / * }
}
}
printf "√2 ≈ %.9f\n", continued-fraction((1, 2 xx *), (1 xx *))[10](Inf);
printf "√2 ≈ %.9f\n", continued-fraction((1, 2 xx *), (1 xx *))[10];
printf "e ≈ %.9f\n", continued-fraction((2, 1 .. *), (1, 1 .. *))[10](Inf);
printf "e ≈ %.9f\n", continued-fraction((2, 1 .. *), (1, 1 .. *))[10];
printf "π ≈ %.9f\n", continued-fraction((3, 6 xx *), ([\+] 1, (8, 16 ... *)))[1000](Inf);</lang>
printf "π ≈ %.9f\n", continued-fraction((3, 6 xx *), ([\+] 1, (8, 16 ... *)))[1000];</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.
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.


'''Extra credit''':
'''Extra credit''':
Line 732: Line 732:
With the same code as above, this could be written:
With the same code as above, this could be written:


<lang Perl 6>printf "π/2 ≈ %.9f\n", continued-fraction((1 X/ 1, 1 .. *), (1 xx *))[1000](Inf);</lang>
<lang Perl 6>printf "π/2 ≈ %.9f\n", continued-fraction((1 X/ 1, 1 .. *), (1 xx *))[1000];</lang>


=={{header|PL/I}}==
=={{header|PL/I}}==