> For the complete documentation index, see [llms.txt](https://trizen.gitbook.io/perl6-rosettacode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://trizen.gitbook.io/perl6-rosettacode/programming_tasks/c/continued_fraction.md).

# Continued fraction

```perl
sub continued-fraction(:@a, :@b, Int :$n = 100)
{
    my $x = @a[$n - 1];
    $x = @a[$_ - 1] + @b[$_] / $x for reverse 1 ..^ $n;
    $x;
}

printf "√2 ≈%.9f\n", continued-fraction(:a(1, |(2 xx *)), :b(Nil, |(1 xx *)));
printf "e  ≈%.9f\n", continued-fraction(:a(2, |(1 .. *)), :b(Nil, 1, |(1 .. *)));
printf "π  ≈%.9f\n", continued-fraction(:a(3, |(6 xx *)), :b(Nil, |((1, 3, 5 ... *) X** 2)));
```

#### Output:

```
√2 ≈ 1.414213562
e  ≈ 2.718281828
π  ≈ 3.141592654
```

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:

Or, more consistently:

Viewed as such, C F n ( x ) {\displaystyle \mathrm {CF} \_{n}(x)} ![{\displaystyle \mathrm{CF}\\\_n(x)}](https://wikimedia.org/api/rest_v1/media/math/render/svg/75b92bbc6f0ca4bee201a8dad88fa1b81da830f3) could be written recursively:

Or in other words:

where f n ( x ) = a n + b n x {\displaystyle f\_{n}(x)=a\_{n}+{\frac {b\_{n}}{x}}} ![{\displaystyle f\\\_n(x) = a\\\_n + \frac{b\\\_n}{x}}](https://wikimedia.org/api/rest_v1/media/math/render/svg/197eec6df33679c436d579fa0a4a165b45bfb6fe)

Raku has a builtin composition operator. We can use it with the triangular reduction metaoperator, and evaluate each resulting function at infinity (any value would do actually, but infinite makes it consistent with this particular task).

```perl
sub continued-fraction(@a, @b) {
    map { .(Inf) }, [\o] map { @a[$_] + @b[$_] / * }, ^Inf
}
 
printf "√2 ≈ %.9f\n", continued-fraction((1, |(2 xx *)), (1 xx *))[10];
printf "e  ≈ %.9f\n", continued-fraction((2, |(1 .. *)), (1, |(1 .. *)))[10];
printf "π  ≈ %.9f\n", continued-fraction((3, |(6 xx *)), ((1, 3, 5 ... *) X** 2))[100];
```

#### Output:

```
√2 ≈ 1.414213552
e  ≈ 2.718281827
π  ≈ 3.141592411
```
