Continued fraction: Difference between revisions

m
(→‎{{header|Perl}}: using persistent private variables)
 
(170 intermediate revisions by 63 users not shown)
Line 16:
 
:<math>\pi = 3 + \cfrac{1}{6 + \cfrac{9}{6 + \cfrac{25}{6 + \ddots}}}</math>
 
 
;See also:
:* &nbsp; [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">F calc(f_a, f_b, =n = 1000)
V r = 0.0
L n > 0
r = f_b(n) / (f_a(n) + r)
n--
R f_a(0) + r
 
print(calc(n -> I n > 0 {2} E 1, n -> 1))
print(calc(n -> I n > 0 {n} E 2, n -> I n > 1 {n - 1} E 1))
print(calc(n -> I n > 0 {6} E 3, n -> (2 * n - 1) ^ 2))</syntaxhighlight>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
DEFINE PTR="CARD"
DEFINE JSR="$20"
DEFINE RTS="$60"
 
PROC CoeffA=*(INT n REAL POINTER res)
[JSR $00 $00 ;JSR to address set by SetCoeffA
RTS]
 
PROC CoeffB=*(INT n REAL POINTER res)
[JSR $00 $00 ;JSR to address set by SetCoeffB
RTS]
 
PROC SetCoeffA(PTR p)
PTR addr
 
addr=CoeffA+1 ;location of address of JSR
PokeC(addr,p)
RETURN
 
PROC SetCoeffB(PTR p)
PTR addr
 
addr=CoeffB+1 ;location of address of JSR
PokeC(addr,p)
RETURN
 
PROC Calc(PTR funA,funB INT count REAL POINTER res)
INT i
REAL a,b,tmp
 
SetCoeffA(funA)
SetCoeffB(funB)
 
IntToReal(0,res)
i=count
WHILE i>0
DO
CoeffA(i,a)
CoeffB(i,b)
RealAdd(a,res,tmp)
RealDiv(b,tmp,res)
i==-1
OD
CoeffA(0,a)
RealAdd(a,res,tmp)
RealAssign(tmp,res)
RETURN
 
PROC sqrtA(INT n REAL POINTER res)
IF n>0 THEN
IntToReal(2,res)
ELSE
IntToReal(1,res)
FI
RETURN
 
PROC sqrtB(INT n REAL POINTER res)
IntToReal(1,res)
RETURN
 
PROC napierA(INT n REAL POINTER res)
IF n>0 THEN
IntToReal(n,res)
ELSE
IntToReal(2,res)
FI
RETURN
 
PROC napierB(INT n REAL POINTER res)
IF n>1 THEN
IntToReal(n-1,res)
ELSE
IntToReal(1,res)
FI
RETURN
 
PROC piA(INT n REAL POINTER res)
IF n>0 THEN
IntToReal(6,res)
ELSE
IntToReal(3,res)
FI
RETURN
 
PROC piB(INT n REAL POINTER res)
REAL tmp
 
IntToReal(2*n-1,tmp)
RealMult(tmp,tmp,res)
RETURN
 
PROC Main()
REAL res
 
Put(125) PutE() ;clear the screen
 
Calc(sqrtA,sqrtB,50,res)
Print(" Sqrt2=") PrintRE(res)
 
Calc(napierA,napierB,50,res)
Print("Napier=") PrintRE(res)
 
Calc(piA,piB,500,res)
Print(" Pi=") PrintRE(res)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Continued_fraction.png Screenshot from Atari 8-bit computer]
<pre>
Sqrt2=1.41421356
Napier=2.71828182
Pi=3.14159265
</pre>
 
=={{header|Ada}}==
(The source text for these examples can also be found on [https://bitbucket.org/ada_on_rosetta_code/solutions Bitbucket].)
<lang Ada>with Ada.Text_IO; use Ada.Text_IO;
procedure ContFract is
type FormType is (Sqrt2, Napier, Pi);
type Floaty is digits 15;
package FIO is new Ada.Text_IO.Float_IO (Floaty);
 
Generic function for estimating continued fractions:
procedure GetCoefs (form : FormType; n : Natural;
<syntaxhighlight lang="ada">generic
coefA : out Natural; coefB : out Natural)
type Scalar is begindigits <>;
case form is
when Sqrt2 =>
if n > 0 then coefA := 2; else coefA := 1; end if;
coefB := 1;
when Napier =>
if n > 0 then coefA := n; else coefA := 2; end if;
if n > 1 then coefB := n - 1; else coefB := 1; end if;
when Pi =>
if n > 0 then coefA := 6; else coefA := 3; end if;
coefB := (2*n - 1)**2;
end case;
end GetCoefs;
 
with function CalcA (formN : FormType; n :in Natural) return Floaty isNatural;
with A,function B (N : in Positive) return Natural;
function Continued_Fraction (Steps : in Natural) return Scalar;</syntaxhighlight>
Temp : Floaty := 0.0;
 
<syntaxhighlight lang="ada">function Continued_Fraction (Steps : in Natural) return Scalar is
function A (N : in Natural) return Scalar is (Scalar (Natural'(A (N))));
function B (N : in Positive) return Scalar is (Scalar (Natural'(B (N))));
 
Fraction : Scalar := 0.0;
begin
for N in reverse Natural range 1 .. Steps loop
Fraction := B (N) / (A (N) + Fraction);
end loop;
return A (0) + Fraction;
end Continued_Fraction;</syntaxhighlight>
Test program using the function above to estimate the square root of 2, Napiers constant and pi:
<syntaxhighlight lang="ada">with Ada.Text_IO;
 
with Continued_Fraction;
 
procedure Test_Continued_Fractions is
type Scalar is digits 15;
 
package Square_Root_Of_2 is
function A (N : in Natural) return Natural is (if N = 0 then 1 else 2);
function B (N : in Positive) return Natural is (1);
 
function Estimate is new Continued_Fraction (Scalar, A, B);
end Square_Root_Of_2;
 
package Napiers_Constant is
function A (N : in Natural) return Natural is (if N = 0 then 2 else N);
function B (N : in Positive) return Natural is (if N = 1 then 1 else N-1);
 
function Estimate is new Continued_Fraction (Scalar, A, B);
end Napiers_Constant;
 
package Pi is
function A (N : in Natural) return Natural is (if N = 0 then 3 else 6);
function B (N : in Positive) return Natural is ((2 * N - 1) ** 2);
 
function Estimate is new Continued_Fraction (Scalar, A, B);
end Pi;
 
package Scalar_Text_IO is new Ada.Text_IO.Float_IO (Scalar);
use Ada.Text_IO, Scalar_Text_IO;
begin
Put (Square_Root_Of_2.Estimate (200), Exp => 0); New_Line;
Put (Napiers_Constant.Estimate (200), Exp => 0); New_Line;
Put (Pi.Estimate (10000), Exp => 0); New_Line;
end Test_Continued_Fractions;</syntaxhighlight>
===Using only Ada 95 features===
This example is exactly the same as the preceding one, but implemented using only Ada 95 features.
<syntaxhighlight lang="ada">generic
type Scalar is digits <>;
 
with function A (N : in Natural) return Natural;
with function B (N : in Positive) return Natural;
function Continued_Fraction_Ada95 (Steps : in Natural) return Scalar;</syntaxhighlight>
 
<syntaxhighlight lang="ada">function Continued_Fraction_Ada95 (Steps : in Natural) return Scalar is
function A (N : in Natural) return Scalar is
begin
forreturn ni in reverseScalar (Natural'(A range 1 .. n loop(N)));
end A;
GetCoefs (form, ni, A, B);
Temp := Floaty (B) / (Floaty (A) + Temp);
end loop;
GetCoefs (form, 0, A, B);
return Floaty (A) + Temp;
end Calc;
 
function B (N : in Positive) return Scalar is
begin
return Scalar (Natural'(B (N)));
end B;
 
Fraction : Scalar := 0.0;
begin
for N in reverse Natural range 1 .. Steps loop
FIO.Put (Calc (Sqrt2, 200), Exp => 0); New_Line;
Fraction := B (N) / (A (N) + Fraction);
FIO.Put (Calc (Napier, 200), Exp => 0); New_Line;
end loop;
FIO.Put (Calc (Pi, 10000), Exp => 0); New_Line;
return A (0) + Fraction;
end ContFract;
end Continued_Fraction_Ada95;</syntaxhighlight>
</lang>
<syntaxhighlight lang="ada">with Ada.Text_IO;
 
with Continued_Fraction_Ada95;
 
procedure Test_Continued_Fractions_Ada95 is
type Scalar is digits 15;
 
package Square_Root_Of_2 is
function A (N : in Natural) return Natural;
function B (N : in Positive) return Natural;
 
function Estimate is new Continued_Fraction_Ada95 (Scalar, A, B);
end Square_Root_Of_2;
 
package body Square_Root_Of_2 is
function A (N : in Natural) return Natural is
begin
if N = 0 then
return 1;
else
return 2;
end if;
end A;
 
function B (N : in Positive) return Natural is
begin
return 1;
end B;
end Square_Root_Of_2;
 
package Napiers_Constant is
function A (N : in Natural) return Natural;
function B (N : in Positive) return Natural;
 
function Estimate is new Continued_Fraction_Ada95 (Scalar, A, B);
end Napiers_Constant;
 
package body Napiers_Constant is
function A (N : in Natural) return Natural is
begin
if N = 0 then
return 2;
else
return N;
end if;
end A;
 
function B (N : in Positive) return Natural is
begin
if N = 1 then
return 1;
else
return N - 1;
end if;
end B;
end Napiers_Constant;
 
package Pi is
function A (N : in Natural) return Natural;
function B (N : in Positive) return Natural;
 
function Estimate is new Continued_Fraction_Ada95 (Scalar, A, B);
end Pi;
 
package body Pi is
function A (N : in Natural) return Natural is
begin
if N = 0 then
return 3;
else
return 6;
end if;
end A;
 
function B (N : in Positive) return Natural is
begin
return (2 * N - 1) ** 2;
end B;
end Pi;
 
package Scalar_Text_IO is new Ada.Text_IO.Float_IO (Scalar);
use Ada.Text_IO, Scalar_Text_IO;
begin
Put (Square_Root_Of_2.Estimate (200), Exp => 0); New_Line;
Put (Napiers_Constant.Estimate (200), Exp => 0); New_Line;
Put (Pi.Estimate (10000), Exp => 0); New_Line;
end Test_Continued_Fractions_Ada95;</syntaxhighlight>
{{out}}
<pre> 1.41421356237310
2.71828182845905</pre>
3.14159265358954</pre>
 
=={{header|ALGOL 68}}==
{{works with|Algol 68 Genie|2.8}}
<syntaxhighlight lang="algol68">
PROC cf = (INT steps, PROC (INT) INT a, PROC (INT) INT b) REAL:
BEGIN
REAL result;
result := 0;
FOR n FROM steps BY -1 TO 1 DO
result := b(n) / (a(n) + result)
OD;
a(0) + result
END;
 
PROC asqr2 = (INT n) INT: (n = 0 | 1 | 2);
PROC bsqr2 = (INT n) INT: 1;
 
PROC anap = (INT n) INT: (n = 0 | 2 | n);
PROC bnap = (INT n) INT: (n = 1 | 1 | n - 1);
 
PROC api = (INT n) INT: (n = 0 | 3 | 6);
PROC bpi = (INT n) INT: (n = 1 | 1 | (2 * n - 1) ** 2);
 
INT precision = 10000;
 
print (("Precision: ", precision, newline));
print (("Sqr(2): ", cf(precision, asqr2, bsqr2), newline));
print (("Napier: ", cf(precision, anap, bnap), newline));
print (("Pi: ", cf(precision, api, bpi)))
</syntaxhighlight>
{{out}}
<pre>
Precision: +10000
Sqr(2): +1.41421356237310e +0
Napier: +2.71828182845905e +0
Pi: +3.14159265358954e +0
</pre>
 
=={{header|Arturo}}==
{{trans|Nim}}
<syntaxhighlight lang="rebol">calc: function [f, n][
[a, b, temp]: 0.0
 
loop n..1 'i [
[a, b]: call f @[i]
temp: b // a + temp
]
[a, b]: call f @[0]
return a + temp
]
 
sqrt2: function [n][
(n > 0)? -> [2.0, 1.0] -> [1.0, 1.0]
]
 
napier: function [n][
a: (n > 0)? -> to :floating n -> 2.0
b: (n > 1)? -> to :floating n-1 -> 1.0
@[a, b]
]
 
Pi: function [n][
a: (n > 0)? -> 6.0 -> 3.0
b: ((2 * to :floating n)-1) ^ 2
@[a, b]
]
 
print calc 'sqrt2 20
print calc 'napier 15
print calc 'Pi 10000</syntaxhighlight>
 
{{out}}
 
<pre>1.414213562373095
2.718281828459046
3.141592653589544</pre>
 
=={{header|ATS}}==
A fairly direct translation of the [[#C|C version]] without using advanced features of the type system:
<syntaxhighlight lang="ats">#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
//
(*
** a coefficient function creates double values from in paramters
*)
typedef coeff_f = int -> double
//
(*
** a continued fraction is described by a record of two coefficent
** functions a and b
*)
typedef frac = @{a= coeff_f, b= coeff_f}
//
(* ****** ****** *)
 
fun calc
(
f: frac, n: int
) : double = let
//
(*
** recursive definition of the approximation
*)
fun loop
(
n: int, r: double
) : double =
(
if n = 0
then f.a(0) + r
else loop (n - 1, f.b(n) / (f.a(n) + r))
// end of [if]
)
//
in
loop (n, 0.0)
end // end of [calc]
 
(* ****** ****** *)
 
val sqrt2 = @{
a= lam (n: int): double => if n = 0 then 1.0 else 2.0
,
b= lam (n: int): double => 1.0
} (* end of [val] *)
 
val napier = @{
a= lam (n: int): double => if n = 0 then 2.0 else 1.0 * n
,
b= lam (n: int): double => if n = 1 then 1.0 else n - 1.0
} (* end of [val] *)
 
val pi = @{
a= lam (n: int): double => if n = 0 then 3.0 else 6.0
,
b= lam (n: int): double => let val x = 2.0 * n - 1 in x * x end
}
 
(* ****** ****** *)
 
implement
main0 () =
(
println! ("sqrt2 = ", calc(sqrt2, 100));
println! ("napier = ", calc(napier, 100));
println! (" pi = ", calc( pi , 100));
) (* end of [main0] *)</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">sqrt2_a(n) ; function definition is as simple as that
{
return n?2.0:1.0
}
 
sqrt2_b(n)
{
return 1.0
}
 
napier_a(n)
{
return n?n:2.0
}
 
napier_b(n)
{
return n>1.0?n-1.0:1.0
}
 
pi_a(n)
{
return n?6.0:3.0
}
 
pi_b(n)
{
return (2.0*n-1.0)**2.0 ; exponentiation operator
}
 
calc(f,expansions)
{
r:=0,i:=expansions
; A nasty trick: the names of the two coefficient functions are generated dynamically
; a dot surrounded by spaces means string concatenation
f_a:=f . "_a",f_b:=f . "_b"
 
while i>0 {
; You can see two dynamic function calls here
r:=%f_b%(i)/(%f_a%(i)+r)
i--
}
 
return %f_a%(0)+r
}
 
Msgbox, % "sqrt 2 = " . calc("sqrt2", 1000) . "`ne = " . calc("napier", 1000) . "`npi = " . calc("pi", 1000)</syntaxhighlight>
Output with Autohotkey v1 (currently 1.1.16.05):
<syntaxhighlight lang="autohotkey">sqrt 2 = 1.414214
e = 2.718282
pi = 3.141593</syntaxhighlight>
Output with Autohotkey v2 (currently alpha 56):
<syntaxhighlight lang="autohotkey">sqrt 2 = 1.4142135623730951
e = 2.7182818284590455
pi = 3.1415926533405418</syntaxhighlight>
Note the far superiour accuracy of v2.
 
=={{header|Axiom}}==
Axiom provides a ContinuedFraction domain:
<langsyntaxhighlight Axiomlang="axiom">get(obj) == convergents(obj).1000 -- utility to extract the 1000th value
get continuedFraction(1, repeating [1], repeating [2]) :: Float
get continuedFraction(2, cons(1,[i for i in 1..]), [i for i in 1..]) :: Float
get continuedFraction(3, [i^2 for i in 1.. by 2], repeating [6]) :: Float</langsyntaxhighlight>
Output:<langsyntaxhighlight Axiomlang="axiom"> (1) 1.4142135623 730950488
Type: Float
 
Line 75 ⟶ 548:
 
(3) 3.1415926538 39792926
Type: Float</langsyntaxhighlight>
The value for <math>\pi</math> has an accuracy to only 9 decimal places after 1000 iterations, with an accuracy to 12 decimal places after 10000 iterations.
 
We could re-implement this, with the same output:<lang Axiom>cf(initial, a, b, n) ==
<syntaxhighlight lang="axiom">cf(initial, a, b, n) ==
n=1 => initial
temp := 0
Line 86 ⟶ 560:
cf(1, repeating [1], repeating [2], 1000) :: Float
cf(2, cons(1,[i for i in 1..]), [i for i in 1..], 1000) :: Float
cf(3, [i^2 for i in 1.. by 2], repeating [6], 1000) :: Float</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> *FLOAT64
@% = &1001010
Line 105 ⟶ 579:
expr$ += STR$(EVAL(a$)) + "+" + STR$(EVAL(b$)) + "/("
UNTIL LEN(expr$) > (65500 - N)
= a0 + b1 / EVAL (expr$ + "1" + STRING$(N, ")"))</langsyntaxhighlight>
{{out}}
'''Output:'''
<pre>
SQR(2) = 1.414213562373095
Line 112 ⟶ 586:
PI = 3.141592653588017
</pre>
 
=={{header|C}}==
{{works with|ANSI C}}
<syntaxhighlight lang="c">/* calculate approximations for continued fractions */
#include <stdio.h>
 
/* kind of function that returns a series of coefficients */
typedef double (*coeff_func)(unsigned n);
 
/* calculates the specified number of expansions of the continued fraction
* described by the coefficient series f_a and f_b */
double calc(coeff_func f_a, coeff_func f_b, unsigned expansions)
{
double a, b, r;
a = b = r = 0.0;
 
unsigned i;
for (i = expansions; i > 0; i--) {
a = f_a(i);
b = f_b(i);
r = b / (a + r);
}
a = f_a(0);
 
return a + r;
}
 
/* series for sqrt(2) */
double sqrt2_a(unsigned n)
{
return n ? 2.0 : 1.0;
}
 
double sqrt2_b(unsigned n)
{
return 1.0;
}
 
/* series for the napier constant */
double napier_a(unsigned n)
{
return n ? n : 2.0;
}
 
double napier_b(unsigned n)
{
return n > 1.0 ? n - 1.0 : 1.0;
}
 
/* series for pi */
double pi_a(unsigned n)
{
return n ? 6.0 : 3.0;
}
 
double pi_b(unsigned n)
{
double c = 2.0 * n - 1.0;
 
return c * c;
}
 
int main(void)
{
double sqrt2, napier, pi;
 
sqrt2 = calc(sqrt2_a, sqrt2_b, 1000);
napier = calc(napier_a, napier_b, 1000);
pi = calc(pi_a, pi_b, 1000);
 
printf("%12.10g\n%12.10g\n%12.10g\n", sqrt2, napier, pi);
 
return 0;
}</syntaxhighlight>
{{out}}
<pre> 1.414213562
2.718281828
3.141592653</pre>
 
=={{header|C sharp|C#}}==
{{trans|Java}}
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
namespace ContinuedFraction {
class Program {
static double Calc(Func<int, int[]> f, int n) {
double temp = 0.0;
for (int ni = n; ni >= 1; ni--) {
int[] p = f(ni);
temp = p[1] / (p[0] + temp);
}
return f(0)[0] + temp;
}
 
static void Main(string[] args) {
List<Func<int, int[]>> fList = new List<Func<int, int[]>>();
fList.Add(n => new int[] { n > 0 ? 2 : 1, 1 });
fList.Add(n => new int[] { n > 0 ? n : 2, n > 1 ? (n - 1) : 1 });
fList.Add(n => new int[] { n > 0 ? 6 : 3, (int) Math.Pow(2 * n - 1, 2) });
 
foreach (var f in fList) {
Console.WriteLine(Calc(f, 200));
}
}
}
}</syntaxhighlight>
{{out}}
<pre>1.4142135623731
2.71828182845905
3.14159262280485</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <tuple>
Line 155 ⟶ 740:
<< calc(pi, 10000) << '\n'
<< std::setprecision(old_prec); // reset precision
}</langsyntaxhighlight>
{{out}}
<pre>
Line 162 ⟶ 747:
3.14159265358954
</pre>
 
=={{header|Chapel}}==
 
Functions don't take other functions as arguments, so I wrapped them in a dummy record each.
<syntaxhighlight lang="chapel">proc calc(f, n) {
var r = 0.0;
 
for k in 1..n by -1 {
var v = f.pair(k);
r = v(2) / (v(1) + r);
}
 
return f.pair(0)(1) + r;
}
 
record Sqrt2 {
proc pair(n) {
return (if n == 0 then 1 else 2,
1);
}
}
 
record Napier {
proc pair(n) {
return (if n == 0 then 2 else n,
if n == 1 then 1 else n - 1);
}
}
record Pi {
proc pair(n) {
return (if n == 0 then 3 else 6,
(2*n - 1)**2);
}
}
 
config const n = 200;
writeln(calc(new Sqrt2(), n));
writeln(calc(new Napier(), n));
writeln(calc(new Pi(), n));</syntaxhighlight>
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(defn cfrac
[a b n]
(letfn [(cfrac-iter [[x k]] [(+ (a k) (/ (b (inc k)) x)) (dec k)])]
(ffirst (take 1 (drop (inc n) (iterate cfrac-iter [1 n]))))))
 
(def sq2 (cfrac #(if (zero? %) 1.0 2.0) (constantly 1.0) 100))
(def e (cfrac #(if (zero? %) 2.0 %) #(if (= 1 %) 1.0 (double (dec %))) 100))
(def pi (cfrac #(if (zero? %) 3.0 6.0) #(let [x (- (* 2.0 %) 1.0)] (* x x)) 900000))
</syntaxhighlight>
{{out}}
<pre>
user=> sq2 e pi
1.4142135623730951
2.7182818284590455
3.141592653589793
</pre>
 
=={{header|COBOL}}==
{{works with|GnuCOBOL}}
 
<syntaxhighlight lang="cobol"> identification division.
program-id. show-continued-fractions.
 
environment division.
configuration section.
repository.
function continued-fractions
function all intrinsic.
 
procedure division.
fractions-main.
 
display "Square root 2 approximately : "
continued-fractions("sqrt-2-alpha", "sqrt-2-beta", 100)
display "Napier constant approximately : "
continued-fractions("napier-alpha", "napier-beta", 40)
display "Pi approximately : "
continued-fractions("pi-alpha", "pi-beta", 10000)
 
goback.
end program show-continued-fractions.
 
*> **************************************************************
identification division.
function-id. continued-fractions.
data division.
working-storage section.
01 alpha-function usage program-pointer.
01 beta-function usage program-pointer.
01 alpha usage float-long.
01 beta usage float-long.
01 running usage float-long.
01 i usage binary-long.
 
linkage section.
01 alpha-name pic x any length.
01 beta-name pic x any length.
01 iterations pic 9 any length.
01 approximation usage float-long.
 
procedure division using
alpha-name beta-name iterations
returning approximation.
 
set alpha-function to entry alpha-name
if alpha-function = null then
display "error: no " alpha-name " function" upon syserr
goback
end-if
set beta-function to entry beta-name
if beta-function = null then
display "error: no " beta-name " function" upon syserr
goback
end-if
 
move 0 to alpha beta running
perform varying i from iterations by -1 until i = 0
call alpha-function using i returning alpha
call beta-function using i returning beta
compute running = beta / (alpha + running)
end-perform
call alpha-function using 0 returning alpha
compute approximation = alpha + running
 
goback.
end function continued-fractions.
 
*> ******************************
identification division.
program-id. sqrt-2-alpha.
 
data division.
working-storage section.
01 result usage float-long.
 
linkage section.
01 iteration usage binary-long unsigned.
 
procedure division using iteration returning result.
if iteration equal 0 then
move 1.0 to result
else
move 2.0 to result
end-if
 
goback.
end program sqrt-2-alpha.
 
*> ******************************
identification division.
program-id. sqrt-2-beta.
 
data division.
working-storage section.
01 result usage float-long.
 
linkage section.
01 iteration usage binary-long unsigned.
 
procedure division using iteration returning result.
move 1.0 to result
 
goback.
end program sqrt-2-beta.
 
*> ******************************
identification division.
program-id. napier-alpha.
 
data division.
working-storage section.
01 result usage float-long.
 
linkage section.
01 iteration usage binary-long unsigned.
 
procedure division using iteration returning result.
if iteration equal 0 then
move 2.0 to result
else
move iteration to result
end-if
 
goback.
end program napier-alpha.
 
*> ******************************
identification division.
program-id. napier-beta.
 
data division.
working-storage section.
01 result usage float-long.
 
linkage section.
01 iteration usage binary-long unsigned.
 
procedure division using iteration returning result.
if iteration = 1 then
move 1.0 to result
else
compute result = iteration - 1.0
end-if
 
goback.
end program napier-beta.
 
*> ******************************
identification division.
program-id. pi-alpha.
 
data division.
working-storage section.
01 result usage float-long.
 
linkage section.
01 iteration usage binary-long unsigned.
 
procedure division using iteration returning result.
if iteration equal 0 then
move 3.0 to result
else
move 6.0 to result
end-if
 
goback.
end program pi-alpha.
 
*> ******************************
identification division.
program-id. pi-beta.
 
data division.
working-storage section.
01 result usage float-long.
 
linkage section.
01 iteration usage binary-long unsigned.
 
procedure division using iteration returning result.
compute result = (2 * iteration - 1) ** 2
 
goback.
end program pi-beta.
</syntaxhighlight>
 
{{out}}
<pre>prompt$ cobc -xj continued-fractions.cob
Square root 2 approximately : 1.414213562373095
Napier constant approximately : 2.718281828459045
Pi approximately : 3.141592653589543</pre>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript"># Compute a continuous fraction of the form
# a0 + b1 / (a1 + b2 / (a2 + b3 / ...
continuous_fraction = (f) ->
Line 198 ⟶ 1,037:
x = 2*n - 1
x * x
p Math.PI, continuous_fraction(fpi)</syntaxhighlight>
{{out}}
</lang>
output
<pre>
> coffee continued_fraction.coffee
Line 216 ⟶ 1,054:
=={{header|Common Lisp}}==
{{trans|C++}}
<langsyntaxhighlight lang="lisp">(defun estimate-continued-fraction (generator n)
(let ((temp 0))
(loop for n1 from n downto 1
Line 239 ⟶ 1,077:
(* (1- (* 2 n))
(1- (* 2 n))))) 10000)
'double-float))</syntaxhighlight>
</lang>
{{out}}
<pre>sqrt(2) = 1.4142135623730947d0
napier's = 2.7182818284590464d0
pi = 3.141592653589543d0</pre>
=={{header|D}}==
<lang d>import std.typecons;
 
=={{header|D}}==
alias Tuple!(int,"a", int,"b") Pair;
<syntaxhighlight lang="d">import std.stdio, std.functional, std.traits;
 
FP calc(FP, F)(in F fun, in int n) pure nothrow if (isCallable!F) {
FP temp = 0;
 
foreach_reverse (immutable ni; 1 .. n + 1) {
immutable p = fun(ni);
temp = cast(FP)p.b[1] / (castFP(FPp[0])p.a + temp);
}
return cast(FP)fun(0).a[0] + temp;
}
 
// int[2] fsqrt2fSqrt2(in int n) pure nothrow {
return [n > 0 ? 2 : 1, 1];
Pair fsqrt2(in int n) pure nothrow {
return Pair(n > 0 ? 2 : 1,
1);
}
 
Pairint[2] fnapierfNapier(in int n) pure nothrow {
return Pair([n > 0 ? n : 2, n > 1 ? (n - 1) : 1];
n > 1 ? (n - 1) : 1);
}
 
Pairint[2] fpifPi(in int n) pure nothrow {
return Pair([n > 0 ? 6 : 3, (2 * n - 1) ^^ 2];
(2 * n - 1) ^^ 2);
}
 
alias print = curry!(writefln, "%.19f");
void main() {
import std.stdio;
 
void main() {
writefln("%.19f", calc!real(&fsqrt2, 200));
writefln("%.19f", calc!real(&fnapierfSqrt2, 200)).print;
writefln("%.19f", calc!real(&fpifNapier, 200)).print;
calc!real(&fPi, 200).print;
}</lang>
}</syntaxhighlight>
{{out}}
<pre>1.4142135623730950487
2.7182818284590452354
3.1415926228048469486</pre>
 
=={{header|dc}}==
 
<syntaxhighlight lang="dc">[20k 0 200 si [li lbx r li lax + / li 1 - dsi 0<:]ds:x 0 lax +]sf
 
[[2q]s2[0<2 1]sa[R1]sb]sr # sqrt(2)
[[R2q]s2[d 0=2]sa[R1q]s1[d 1=1 1-]sb]se # e
[[3q]s3[0=3 6]sa[2*1-d*]sb]sp # pi
 
c lex lfx p
lrx lfx p
lpx lfx p</syntaxhighlight>
{{out}}
<pre>3.14159262280484694855
1.41421356237309504880
2.71828182845904523536</pre>
 
20 decimal places and 200 iterations.
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
numfmt 8 0
func calc_sqrt .
n = 100
sum = n
while n >= 1
a = 1
if n > 1
a = 2
.
b = 1
sum = a + b / sum
n -= 1
.
return sum
.
func calc_e .
n = 100
sum = n
while n >= 1
a = 2
if n > 1
a = n - 1
.
b = 1
if n > 1
b = n - 1
.
sum = a + b / sum
n -= 1
.
return sum
.
func calc_pi .
n = 100
sum = n
while n >= 1
a = 3
if n > 1
a = 6
.
b = 2 * n - 1
b *= b
sum = a + b / sum
n -= 1
.
return sum
.
print calc_sqrt
print calc_e
print calc_pi
</syntaxhighlight>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">
defmodule CFrac do
def compute([a | _], []), do: a
def compute([a | as], [b | bs]), do: a + b/compute(as, bs)
 
def sqrt2 do
a = [1 | Stream.cycle([2]) |> Enum.take(1000)]
b = Stream.cycle([1]) |> Enum.take(1000)
IO.puts compute(a, b)
end
 
def exp1 do
a = [2 | Stream.iterate(1, &(&1 + 1)) |> Enum.take(1000)]
b = [1 | Stream.iterate(1, &(&1 + 1)) |> Enum.take(999)]
IO.puts compute(a, b)
end
 
def pi do
a = [3 | Stream.cycle([6]) |> Enum.take(1000)]
b = 1..1000 |> Enum.map(fn k -> (2*k - 1)**2 end)
IO.puts compute(a, b)
end
end
</syntaxhighlight>
 
{{out}}
<pre>
>elixir -e CFrac.sqrt2()
1.4142135623730951
 
>elixir -e CFrac.exp1()
2.7182818284590455
 
>elixir -e CFrac.pi()
3.141592653340542
</pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module(continued).
-compile([export_all]).
 
pi_a (0) -> 3;
pi_a (_N) -> 6.
 
pi_b (N) ->
(2*N-1)*(2*N-1).
 
sqrt2_a (0) ->
1;
sqrt2_a (_N) ->
2.
 
sqrt2_b (_N) ->
1.
 
nappier_a (0) ->
2;
nappier_a (N) ->
N.
 
nappier_b (1) ->
1;
nappier_b (N) ->
N-1.
 
continued_fraction(FA,_FB,0) -> FA(0);
continued_fraction(FA,FB,N) ->
continued_fraction(FA,FB,N-1,FB(N)/FA(N)).
 
continued_fraction(FA,_FB,0,Acc) -> FA(0) + Acc;
continued_fraction(FA,FB,N,Acc) ->
continued_fraction(FA,FB,N-1,FB(N)/ (FA(N) + Acc)).
 
test_pi (N) ->
continued_fraction(fun pi_a/1,fun pi_b/1,N).
 
test_sqrt2 (N) ->
continued_fraction(fun sqrt2_a/1,fun sqrt2_b/1,N).
 
test_nappier (N) ->
continued_fraction(fun nappier_a/1,fun nappier_b/1,N).
</syntaxhighlight>
 
{{out}}
<syntaxhighlight lang="erlang">
29> continued:test_pi(1000).
3.141592653340542
30> continued:test_sqrt2(1000).
1.4142135623730951
31> continued:test_nappier(1000).
2.7182818284590455
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
===The Functions===
<syntaxhighlight lang="fsharp">
// I provide four functions:-
// cf2S general purpose continued fraction to sequence of float approximations
// cN2S Normal continued fractions (a-series always 1)
// cfSqRt uses cf2S to calculate sqrt of float
// π takes a sequence of b values returning the next until the list is exhausted after which it injects infinity
// Nigel Galloway: December 19th., 2018
let cf2S α β=let n0,g1,n1,g2=β(),α(),β(),β()
seq{let (Π:decimal)=g1/n1 in yield n0+Π; yield! Seq.unfold(fun(n,g,Π)->let a,b=α(),β() in let Π=Π*g/n in Some(n0+Π,(b+a/n,b+a/g,Π)))(g2+α()/n1,g2,Π)}
let cN2S = cf2S (fun()->1M)
let cfSqRt n=(cf2S (fun()->n-1M) (let mutable n=false in fun()->if n then 2M else (n<-true; 1M)))
let π n=let mutable π=n in (fun ()->match π with h::t->π<-t; h |_->9999999999999999999999999999M)
</syntaxhighlight>
===The Tasks===
<syntaxhighlight lang="fsharp">
cfSqRt 2M |> Seq.take 10 |> Seq.pairwise |> Seq.iter(fun(n,g)->printfn "%1.14f < √2 < %1.14f" (min n g) (max n g))
</syntaxhighlight>
{{out}}
<pre>
1.40000000000000 < √2 < 1.50000000000000
1.40000000000000 < √2 < 1.41666666666667
1.41379310344828 < √2 < 1.41666666666667
1.41379310344828 < √2 < 1.41428571428571
1.41420118343195 < √2 < 1.41428571428571
1.41420118343195 < √2 < 1.41421568627451
1.41421319796954 < √2 < 1.41421568627451
1.41421319796954 < √2 < 1.41421362489487
1.41421355164605 < √2 < 1.41421362489487
</pre>
<syntaxhighlight lang="fsharp">
cfSqRt 0.25M |> Seq.take 30 |> Seq.iter (printfn "%1.14f")
</syntaxhighlight>
{{out}}
<pre>
0.62500000000000
0.53846153846154
0.51250000000000
0.50413223140496
0.50137362637363
0.50045745654163
0.50015243902439
0.50005080784473
0.50001693537461
0.50000564506114
0.50000188167996
0.50000062722587
0.50000020907520
0.50000006969172
0.50000002323057
0.50000000774352
0.50000000258117
0.50000000086039
0.50000000028680
0.50000000009560
0.50000000003187
0.50000000001062
0.50000000000354
0.50000000000118
0.50000000000039
0.50000000000013
0.50000000000004
0.50000000000001
0.50000000000000
0.50000000000000
</pre>
<syntaxhighlight lang="fsharp">
let aπ()=let mutable n=0M in (fun ()->n<-n+1M;let b=n+n-1M in b*b)
let bπ()=let mutable n=true in (fun ()->match n with true->n<-false;3M |_->6M)
cf2S (aπ()) (bπ()) |> Seq.take 10 |> Seq.pairwise |> Seq.iter(fun(n,g)->printfn "%1.14f < π < %1.14f" (min n g) (max n g))
</syntaxhighlight>
{{out}}
<pre>
3.13333333333333 < π < 3.16666666666667
3.13333333333333 < π < 3.14523809523810
3.13968253968254 < π < 3.14523809523810
3.13968253968254 < π < 3.14271284271284
3.14088134088134 < π < 3.14271284271284
3.14088134088134 < π < 3.14207181707182
3.14125482360776 < π < 3.14207181707182
3.14125482360776 < π < 3.14183961892940
3.14140671849650 < π < 3.14183961892940
</pre>
<syntaxhighlight lang="fsharp">
let pi = π [3M;7M;15M;1M;292M;1M;1M;1M;2M;1M;3M;1M;14M;2M;1M;1M;2M;2M;2M;2M]
cN2S pi |> Seq.take 10 |> Seq.pairwise |> Seq.iter(fun(n,g)->printfn "%1.14f < π < %1.14f" (min n g) (max n g))
</syntaxhighlight>
{{out}}
<pre>
3.14150943396226 < π < 3.14285714285714
3.14150943396226 < π < 3.14159292035398
3.14159265301190 < π < 3.14159292035398
3.14159265301190 < π < 3.14159265392142
3.14159265346744 < π < 3.14159265392142
3.14159265346744 < π < 3.14159265361894
3.14159265358108 < π < 3.14159265361894
3.14159265358108 < π < 3.14159265359140
3.14159265358939 < π < 3.14159265359140
</pre>
<syntaxhighlight lang="fsharp">
let ae()=let mutable n=0.5M in (fun ()->match n with 0.5M->n<-0M; 1M |_->n<-n+1M; n)
let be()=let mutable n=0.5M in (fun ()->match n with 0.5M->n<-0M; 2M |_->n<-n+1M; n)
cf2S (ae()) (be()) |> Seq.take 10 |> Seq.pairwise |> Seq.iter(fun(n,g)->printfn "%1.14f < e < %1.14f" (min n g) (max n g))
</syntaxhighlight>
{{out}}
<pre>
2.66666666666667 < e < 3.00000000000000
2.66666666666667 < e < 2.72727272727273
2.71698113207547 < e < 2.72727272727273
2.71698113207547 < e < 2.71844660194175
2.71826333176026 < e < 2.71844660194175
2.71826333176026 < e < 2.71828369389345
2.71828165766640 < e < 2.71828369389345
2.71828165766640 < e < 2.71828184277783
2.71828182735187 < e < 2.71828184277783
</pre>
===Apéry's constant===
See [https://tpiezas.wordpress.com/2012/05/04/continued-fractions-for-zeta2-and-zeta3/ Continued fractions for Zeta(2) and Zeta(3)] section II. Zeta(3)
<syntaxhighlight lang="fsharp">
let aπ()=let mutable n=0 in (fun ()->n<-n+1;-decimal(pown n 6))
let bπ()=let mutable n=0M in (fun ()->n<-n+1M; (2M*n-1M)*(17M*n*n-17M*n+5M))
cf2S (aπ()) (bπ()) |>Seq.map(fun n->6M/n) |> Seq.take 10 |> Seq.pairwise |> Seq.iter(fun(n,g)->printfn "%1.20f < p < %- 1.20f" (min n g) (max n g));;
</syntaxhighlight>
{{out}}
<pre>
1.20205479452054794521 < p < 1.20205690119184928874
1.20205690119184928874 < p < 1.20205690315781676650
1.20205690315781676650 < p < 1.20205690315959270361
1.20205690315959270361 < p < 1.20205690315959428400
1.20205690315959428400 < p < 1.20205690315959428540
1.20205690315959428540 < p < 1.20205690315959428540
1.20205690315959428540 < p < 1.20205690315959428540
1.20205690315959428540 < p < 1.20205690315959428540
1.20205690315959428540 < p < 1.20205690315959428540
</pre>
 
=={{header|Factor}}==
''cfrac-estimate'' uses [[Arithmetic/Rational|rational arithmetic]] and never truncates the intermediate result. When ''terms'' is large, ''cfrac-estimate'' runs slow because numerator and denominator grow big.
<syntaxhighlight lang="factor">USING: arrays combinators io kernel locals math math.functions
 
<lang factor>USING: arrays combinators io kernel locals math math.functions
math.ranges prettyprint sequences ;
IN: rosetta.cfrac
Line 353 ⟶ 1,488:
PRIVATE>
 
MAIN: main</langsyntaxhighlight>
 
{{out}}
<pre> Square root of 2: 1.414213562373095048801688724209
Napier's constant: 2.718281828459045235360287471352
Pi: 3.1415926538</pre>
 
=={{header|Felix}}==
<syntaxhighlight lang="felix">fun pi (n:int) : (double*double) =>
let a = match n with | 0 => 3.0 | _ => 6.0 endmatch in
let b = pow(2.0 * n.double - 1.0, 2.0) in
(a,b);
 
fun sqrt_2 (n:int) : (double*double) =>
let a = match n with | 0 => 1.0 | _ => 2.0 endmatch in
let b = 1.0 in
(a,b);
 
fun napier (n:int) : (double*double) =>
let a = match n with | 0 => 2.0 | _ => n.double endmatch in
let b = match n with | 1 => 1.0 | _ => (n.double - 1.0) endmatch in
(a,b);
 
fun cf_iter (steps:int) (f:int -> double*double) = {
var acc = 0.0;
for var n in steps downto 0 do
var a, b = f(n);
acc = if (n > 0) then (b / (a + acc)) else (acc + a);
done
return acc;
}
 
println$ cf_iter 200 sqrt_2; // => 1.41421
println$ cf_iter 200 napier; // => 2.71818
println$ cf_iter 1000 pi; // => 3.14159</syntaxhighlight>
 
=={{header|Forth}}==
{{trans|D}}
<langsyntaxhighlight lang="forth">: fsqrt2 1 s>f 0> if 2 s>f else fdup then ;
: fnapier dup dup 1 > if 1- else drop 1 then s>f dup 1 < if drop 2 then s>f ;
: fpi dup 2* 1- dup * s>f 0> if 6 else 3 then s>f ;
Line 370 ⟶ 1,533:
do i over execute frot f+ f/ -1 +loop
0 swap execute fnip f+ \ calcucate for 0
;</langsyntaxhighlight>
{{out}}
<pre>
Line 380 ⟶ 1,543:
ok
</pre>
 
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">module continued_fractions
implicit none
integer, parameter :: long = selected_real_kind(7,99)
 
type continued_fraction
integer :: a0, b1
procedure(series), pointer, nopass :: a, b
end type
 
interface
pure function series (n)
integer, intent(in) :: n
integer :: series
end function
end interface
 
contains
 
pure function define_cf (a0,a,b1,b) result(x)
integer, intent(in) :: a0
procedure(series) :: a
integer, intent(in), optional :: b1
procedure(series), optional :: b
type(continued_fraction) :: x
x%a0 = a0
x%a => a
if ( present(b1) ) then
x%b1 = b1
else
x%b1 = 1
end if
if ( present(b) ) then
x%b => b
else
x%b => const_1
end if
end function define_cf
 
pure integer function const_1(n)
integer,intent(in) :: n
const_1 = 1
end function
 
pure real(kind=long) function output(x,iterations)
type(continued_fraction), intent(in) :: x
integer, intent(in) :: iterations
integer :: i
output = x%a(iterations)
do i = iterations-1,1,-1
output = x%a(i) + (x%b(i+1) / output)
end do
output = x%a0 + (x%b1 / output)
end function output
end module continued_fractions
 
 
program examples
use continued_fractions
 
type(continued_fraction) :: sqr2,napier,pi
 
sqr2 = define_cf(1,a_sqr2)
napier = define_cf(2,a_napier,1,b_napier)
pi = define_cf(3,a=a_pi,b=b_pi)
 
write (*,*) output(sqr2,10000)
write (*,*) output(napier,10000)
write (*,*) output(pi,10000)
 
contains
 
pure integer function a_sqr2(n)
integer,intent(in) :: n
a_sqr2 = 2
end function
 
pure integer function a_napier(n)
integer,intent(in) :: n
a_napier = n
end function
 
pure integer function b_napier(n)
integer,intent(in) :: n
b_napier = n-1
end function
 
pure integer function a_pi(n)
integer,intent(in) :: n
a_pi = 6
end function
 
pure integer function b_pi(n)
integer,intent(in) :: n
b_pi = (2*n-1)*(2*n-1)
end function
 
end program examples</syntaxhighlight>
{{out}}
<pre>
1.4142135623730951
2.7182818284590455
3.1415926535895435
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">#define MAX 70000
 
function sqrt2_a( n as uinteger ) as uinteger
return iif(n,2,1)
end function
 
function sqrt2_b( n as uinteger ) as uinteger
return 1
end function
 
function napi_a( n as uinteger ) as uinteger
return iif(n,n,2)
end function
 
function napi_b( n as uinteger ) as uinteger
return iif(n>1,n-1,1)
end function
 
function pi_a( n as uinteger ) as uinteger
return iif(n,6,3)
end function
 
function pi_b( n as uinteger ) as uinteger
return (2*n-1)^2
end function
 
function calc_contfrac( an as function (as uinteger) as uinteger, bn as function (as uinteger) as uinteger, byval iter as uinteger ) as double
dim as double r
dim as integer i
for i = iter to 1 step -1
r = bn(i)/(an(i)+r)
next i
return an(0)+r
end function
 
print calc_contfrac( @sqrt2_a, @sqrt2_b, MAX )
print calc_contfrac( @napi_a, @napi_b, MAX )
print calc_contfrac( @pi_a, @pi_b, MAX )</syntaxhighlight>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Continued_fraction}}
 
'''Solution'''
 
The following function definition creates a continued fraction:
 
[[File:Fōrmulæ - Continued fraction 01.png]]
 
The function accepts the following parameters:
 
{| class="wikitable" style="margin:auto"
|-
! Parameter !! Description
|-
| a₀ || Value for a₀
|-
| λa || Lambda expression to define aᵢ
|-
| λb || Lambda expression to define bᵢ
|-
| depth || Depth to calculate the continued fraction
|}
 
Since Fōrmulæ arithmetic simplifies numeric results as they are generated, the result is not a continued fraction by default.
 
If we want to create the structure, we can introduce the parameters as string or text expressions (or lambda expressions that produce them). Because string or text expressions are not reduced when they are operands of additions and divisions, the structure is preserved, such as follows:
 
[[File:Fōrmulæ - Continued fraction 02.png]]
 
[[File:Fōrmulæ - Continued fraction 03.png]]
 
'''Case 1.''' <math>\sqrt 2</math>
 
In this case
 
* a₀ is 1
* λa is n ↦ 2
* λb is n ↦ 1
 
Let us show the results as a table, for several levels of depth (1 to 10).
 
The columns are:
 
* The depth
* The "textual" call, in order to generate the structure
* The normal (numeric) call. Since arithmetic operations are exact by default, it is usually a rational number.
* The value of the normal (numeric) call, forced to be shown as a decimal number, by using the Math.Numeric expression (the N(x) expression)
 
[[File:Fōrmulæ - Continued fraction 04.png]]
 
[[File:Fōrmulæ - Continued fraction 05.png]]
 
'''Case 2.''' <math>e</math>
 
In this case
 
* a₀ is 2
* λa is n ↦ n
* λb is n ↦ 1 if n = 1, n - 1 elsewhere
 
[[File:Fōrmulæ - Continued fraction 06.png]]
 
[[File:Fōrmulæ - Continued fraction 07.png]]
 
'''Case 3.''' <math>\pi</math>
 
In this case
 
* a₀ is 3
* λa is n ↦ 6
* λb is n ↦ 2(n - 1)²
 
[[File:Fōrmulæ - Continued fraction 08.png]]
 
[[File:Fōrmulæ - Continued fraction 09.png]]
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 433 ⟶ 1,822:
fmt.Println("nap: ", cfNap(20).real())
fmt.Println("pi: ", cfPi(20).real())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 440 ⟶ 1,829:
pi: 3.141623806667839
</pre>
 
=={{header|Groovy}}==
{{trans|Java}}
<syntaxhighlight lang="groovy">import java.util.function.Function
 
import static java.lang.Math.pow
 
class Test {
static double calc(Function<Integer, Integer[]> f, int n) {
double temp = 0
 
for (int ni = n; ni >= 1; ni--) {
Integer[] p = f.apply(ni)
temp = p[1] / (double) (p[0] + temp)
}
return f.apply(0)[0] + temp
}
 
static void main(String[] args) {
List<Function<Integer, Integer[]>> fList = new ArrayList<>()
fList.add({ n -> [n > 0 ? 2 : 1, 1] })
fList.add({ n -> [n > 0 ? n : 2, n > 1 ? (n - 1) : 1] })
fList.add({ n -> [n > 0 ? 6 : 3, (int) pow(2 * n - 1, 2)] })
 
for (Function<Integer, Integer[]> f : fList)
System.out.println(calc(f, 200))
}
}</syntaxhighlight>
{{out}}
<pre>1.4142135623730951
2.7182818284590455
3.141592622804847</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (unfoldr)
import Data.Char (intToDigit)
 
-- continued fraction represented as a (possibly infinite) list of pairs
sqrt2, napier, myPi :: [(Integer, Integer)]
sqrt2 = zip (1 : [2,2 ..]) [1,1 ..]
 
napier = zip (2 : [1..]) (1 : [1..])
myPinapier = zip (32 : [6,61 ..]) (map1 (^2): [1,3 ..])
 
myPi = zip (3 : [6,6 ..]) ((^ 2) <$> [1,3 ..])
 
-- approximate a continued fraction after certain number of iterations
approxCF
approxCF :: (Integral a, Fractional b) => Int -> [(a, a)] -> b
:: (Integral a, Fractional b)
approxCF t =
=> Int -> [(a, a)] -> b
foldr (\(a,b) z -> fromIntegral a + fromIntegral b / z) 1 . take t
approxCF t = foldr (\(a, b) z -> fromIntegral a + fromIntegral b / z) 1 . take t
 
-- infinite decimal representation of a real number
decString :: RealFrac a => a -> String
:: RealFrac a
decString frac = show i ++ '.' : decString' f where
=> a -> String
(i,f) = properFraction frac
decString frac = show i ++ '.' : decString_ f
decString' = map intToDigit . unfoldr (Just . properFraction . (10*))
where
(i, f) = properFraction frac
decString_ = map intToDigit . unfoldr (Just . properFraction . (10 *))
 
main :: IO ()
main =
main = mapM_ (putStrLn . take 200 . decString .
mapM_
(approxCF 950 :: [(Integer, Integer)] -> Rational))
(putStrLn .
[sqrt2, napier, myPi]</lang>
take 200 . decString . (approxCF 950 :: [(Integer, Integer)] -> Rational))
[sqrt2, napier, myPi]</syntaxhighlight>
{{out}}
<pre>
Line 472 ⟶ 1,901:
3.141592653297590947683406834261190738869139611505752231394089152890909495973464508817163306557131591579057202097715021166512662872910519439747609829479577279606075707015622200744006783543589980682386
</pre>
<syntaxhighlight lang="haskell">import Data.Ratio ((%), denominator, numerator)
 
<lang haskell>import Data.RatioBool (bool)
 
-- ignoring the task-given pi sequence: sucky convergence
-- pie = zip (3:repeat 6) (map (^2) [1,3..])
pie = zip (0 : [1,3 ..]) (4 : map (^ 2) [1 ..])
 
sqrt2 = zip (1 : repeat 2) (repeat 1)
 
pie napier = zip (02 : [1,3 ..]) (41 :map (^2) [1 ..])
sqrt2 = zip (1:repeat 2) (repeat 1)
napier = zip (2:[1..]) (1:[1..])
 
-- truncate after n terms
cf2rat n = foldr (\(a, b) f -> (a % 1) + ((b % 1) / f)) (1 % 1) . take n
 
-- truncate after error is at most 1/p
cf2rat_p p s = f $ map ((\i -> (cf2rat i s, cf2rat (1 + i) s)) $ map. (2 ^)) [0 ..]
where
where f ((x,y):ys) = if abs (x-y) < (1/fromIntegral p) then x else f ys
f ((x, y):ys)
| abs (x - y) < (1 / fromIntegral p) = x
| otherwise = f ys
 
-- returns a decimal string of n digits after the dot; all digits should
-- be correct (doesn't mean it's the best approximation! the decimal
-- string is simply truncated to given digits: pi=3.141 instead of 3.142)
cf2dec n = (ratstr n) . cf2rat_p (10 ^ n) where
where
ratstr l a = (show t) ++ '.':fracstr l n d where
ratstr l a = show t ++ '.' : fracstr l n d
d = denominator a
where
(t, n) = quotRem (numerator a) d
d = denominator a
fracstr 0 _ _ = []
fracstr l n d = (show t)++ fracstr (l-1) n1 d where (t,n1 n) = quotRem (10numerator * na) d
fracstr 0 _ _ = []
fracstr l n d = show t ++ fracstr (l - 1) n1 d
where
(t, n1) = quotRem (10 * n) d
 
main =:: doIO ()
main = mapM_ putStrLn [cf2dec 200 sqrt2, cf2dec 200 napier, cf2dec 200 pie]</syntaxhighlight>
putStrLn $ cf2dec 200 sqrt2
 
putStrLn $ cf2dec 200 napier
=={{header|Icon}}==
putStrLn $ cf2dec 200 pie</lang>
<syntaxhighlight lang="icon">
$define EVAL_DEPTH 100
 
# A generalized continued fraction, represented by two functions. Each
# function maps from an index to a floating-point value.
record continued_fraction (a, b)
 
procedure main ()
writes (" sqrt 2.0 = ")
write (evaluate_continued_fraction (continued_fraction (sqrt2_a, sqrt2_b),
EVAL_DEPTH))
writes (" e = ")
write (evaluate_continued_fraction (continued_fraction (e_a, e_b),
EVAL_DEPTH))
writes (" pi = ")
write (evaluate_continued_fraction (continued_fraction (pi_a, pi_b),
EVAL_DEPTH))
end
 
procedure evaluate_continued_fraction (frac, depth)
local i, retval
retval := frac.a (depth)
every i := depth to 1 by -1 do {
retval := frac.a (i - 1) + (frac.b (i) / retval)
}
return retval
end
 
procedure sqrt2_a (i)
return (if i = 0 then 1.0 else 2.0)
end
 
procedure sqrt2_b (i)
return 1.0
end
 
procedure e_a (i)
return (if i = 0 then 2.0 else real (i))
end
 
procedure e_b (i)
return (if i = 1 then 1.0 else real (i - 1))
end
 
procedure pi_a (i)
return (if i = 0 then 3.0 else 6.0)
end
 
procedure pi_b (i)
return real (((2 * i) - 1)^2)
end
</syntaxhighlight>
 
{{out}}
<pre>$ icon continued-fraction-task.icn
sqrt 2.0 = 1.414213562
e = 2.718281828
pi = 3.141592411
</pre>
 
=={{header|J}}==
<syntaxhighlight lang="j"> cfrac=: +`% / NB. Evaluate a list as a continued fraction
<lang J>
cfrac=: +`% / NB. Evaluate a list as a continued fraction
 
sqrt2=: cfrac 1 1,200$2 1x
Line 519 ⟶ 2,014:
1.4142135623730950488016887242096980785696718753769480731766797379907324784621205551109457595775322165
3.1415924109
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274</syntaxhighlight>
</lang>
 
Note that there are two kinds of continued fractions. The kind here where we alternate between '''a''' and '''b''' values, but in some other tasks '''b''' is always 1 (and not included in the list we use to represent the continued fraction). The other kind is evaluated in J using <code>(+%)/</code> instead of <code>+`%/</code>.
=={{header|Mathematica}}==
 
<lang Mathematica>
=={{header|Java}}==
sqrt2=Function[n,{1,Transpose@{Array[2&,n],Array[1&,n]}}];
{{trans|D}}
{{works with|Java|8}}
<syntaxhighlight lang="java">import static java.lang.Math.pow;
import java.util.*;
import java.util.function.Function;
 
public class Test {
static double calc(Function<Integer, Integer[]> f, int n) {
double temp = 0;
 
for (int ni = n; ni >= 1; ni--) {
Integer[] p = f.apply(ni);
temp = p[1] / (double) (p[0] + temp);
}
return f.apply(0)[0] + temp;
}
 
public static void main(String[] args) {
List<Function<Integer, Integer[]>> fList = new ArrayList<>();
fList.add(n -> new Integer[]{n > 0 ? 2 : 1, 1});
fList.add(n -> new Integer[]{n > 0 ? n : 2, n > 1 ? (n - 1) : 1});
fList.add(n -> new Integer[]{n > 0 ? 6 : 3, (int) pow(2 * n - 1, 2)});
 
for (Function<Integer, Integer[]> f : fList)
System.out.println(calc(f, 200));
}
}</syntaxhighlight>
<pre>1.4142135623730951
2.7182818284590455
3.141592622804847</pre>
 
=={{header|jq}}==
{{ works with | jq | 1.4 }}
We take one of the points of interest here to be the task of
representing the infinite series a0, a1, .... and b0, b1, .... compactly,
preferably functionally. For the type of series typically encountered in continued fractions,
this is most readily accomplished in jq 1.4 using a filter (a function), here called "next", which, given the triple [i, [a[i], b[i]], will produce the next triple [i+1, a[i+1], b[i+1]].
 
Another point of interest is avoiding having to specify the number
of iterations. The approach adopted here allows one to specify the
desired accuracy; in some cases, it is feasible to specify that the
computation should continue until the accuracy permitted by the
underlying floating point representation is achieved. This is done
by specifying delta as 0, as shown in the examples.
 
We therefore proceed in two steps: continued_fraction( first; next; count ) computes an approximation
based on the first "count" terms; and then continued_fraction_delta(first; next; delta)
computes the continued fraction until the difference in approximations is less than or equal to delta,
which may be 0, as previously noted.
<syntaxhighlight lang="jq">
# "first" is the first triple, e.g. [1,a,b];
# "count" specifies the number of terms to use.
def continued_fraction( first; next; count ):
# input: [i, a, b]
def cf:
if .[0] == count then 0
else next as $ab
| .[1] + (.[2] / ($ab | cf))
end ;
first | cf;
 
# "first" and "next" are as above;
# if delta is 0 then continue until there is no detectable change.
def continued_fraction_delta(first; next; delta):
def abs: if . < 0 then -. else . end;
def cf:
# state: [n, prev]
.[0] as $n | .[1] as $prev
| continued_fraction(first; next; $n+1) as $this
| if $prev == null then [$n+1, $this] | cf
elif delta <= 0 and ($prev == $this) then $this
elif (($prev - $this)|abs) <= delta then $this
else [$n+1, $this] | cf
end;
[2,null] | cf;
</syntaxhighlight>
'''Examples''':
 
The convergence for pi is slow so we select delta = 1e-12 in that case.
<syntaxhighlight lang="jq">"Value : Direct : Continued Fraction",
"2|sqrt : \(2|sqrt) : \(continued_fraction_delta( [1,1,1]; [.[0]+1, 2, 1]; 0))",
"1|exp : \(1|exp) : \(2 + (1 / (continued_fraction_delta( [1,1,1]; [.[0]+1, .[1]+1, .[2]+1]; 0))))",
"pi : \(1|atan * 4) : \(continued_fraction_delta( [1,3,1]; .[0]+1 | [., 6, ((2*. - 1) | (.*.))]; 1e-12)) (1e-12)"
</syntaxhighlight>
{{Out}}
<syntaxhighlight lang="sh">$ jq -M -n -r -f Continued_fraction.jq
Value : Direct : Continued Fraction
2|sqrt : 1.4142135623730951 : 1.4142135623730951
1|exp : 2.718281828459045 : 2.7182818284590455
pi : 3.141592653589793 : 3.1415926535892935 (1e-12)</syntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|1.8.5}}
High performant lazy evaluation on demand with Julias iterators.
<syntaxhighlight lang="julia">
using .Iterators: countfrom, flatten, repeated, zip
using .MathConstants: ℯ
using Printf
 
function cf(a₀, a, b = repeated(1))
m = BigInt[a₀ 1; 1 0]
for (aᵢ, bᵢ) ∈ zip(a, b)
m *= [aᵢ 1; bᵢ 0]
isapprox(m[1]/m[2], m[3]/m[4]; atol = 1e-12) && break
end
m[1]/m[2]
end
 
out((k, v)) = @printf "%2s: %.12f ≈ %.12f\n" k v eval(k)
 
foreach(out, (
:(√2) => cf(1, repeated(2)),
:ℯ => cf(2, countfrom(), flatten((1, countfrom()))),
:π => cf(3, repeated(6), (k^2 for k ∈ countfrom(1, 2)))))
</syntaxhighlight>
{{out}}
<pre>√2: 1.414213562373 ≈ 1.414213562373
ℯ: 2.718281828459 ≈ 2.718281828459
π: 3.141592653590 ≈ 3.141592653590</pre>
 
=={{header|Klong}}==
<syntaxhighlight lang="k">
cf::{[f g i];f::x;g::y;i::z;
f(0)+z{i::i-1;g(i+1)%f(i+1)+x}:*0}
cf({:[0=x;1;2]};{x;1};1000)
cf({:[0=x;2;x]};{:[x>1;x-1;x]};1000)
cf({:[0=x;3;6]};{((2*x)-1)^2};1000)
</syntaxhighlight>
{{out}}
<pre>
:triad
1.41421356237309504
2.71828182845904523
3.14159265334054205
</pre>
 
=={{header|Kotlin}}==
{{trans|D}}
<syntaxhighlight lang="scala">// version 1.1.2
 
typealias Func = (Int) -> IntArray
 
fun calc(f: Func, n: Int): Double {
var temp = 0.0
for (i in n downTo 1) {
val p = f(i)
temp = p[1] / (p[0] + temp)
}
return f(0)[0] + temp
}
 
fun main(args: Array<String>) {
val pList = listOf<Pair<String, Func>>(
"sqrt(2)" to { n -> intArrayOf(if (n > 0) 2 else 1, 1) },
"e " to { n -> intArrayOf(if (n > 0) n else 2, if (n > 1) n - 1 else 1) },
"pi " to { n -> intArrayOf(if (n > 0) 6 else 3, (2 * n - 1) * (2 * n - 1)) }
)
for (pair in pList) println("${pair.first} = ${calc(pair.second, 200)}")
}</syntaxhighlight>
 
{{out}}
<pre>
sqrt(2) = 1.4142135623730951
e = 2.7182818284590455
pi = 3.141592622804847
</pre>
 
=={{header|Lambdatalk}}==
 
<syntaxhighlight lang="scheme">
 
{def gcf
{def gcf.rec
{lambda {:f :n :r}
{if {< :n 1}
then {+ {car {:f 0}} :r}
else {gcf.rec :f
{- :n 1}
{let { {:r :r}
{:ab {:f :n}}
} {/ {cdr :ab}
{+ {car :ab} :r}} }}}}}
{lambda {:f :n}
{gcf.rec :f :n 0}}}
 
{def phi
{lambda {:n}
{cons 1 1}}}
 
{gcf phi 50}
-> 1.618033988749895
 
{def sqrt2
{lambda {:n}
{cons {if {> :n 0} then 2 else 1} 1}}}
 
{gcf sqrt2 25}
-> 1.4142135623730951
 
{def napier
{lambda {:n}
{cons {if {> :n 0} then :n else 2} {if {> :n 1} then {- :n 1} else 1} }}}
 
{gcf napier 20}
-> 2.7182818284590455
 
{def fpi
{lambda {:n}
{cons {if {> :n 0} then 6 else 3} {pow {- {* 2 :n} 1} 2} }}}
 
{gcf fpi 500}
-> 3.1415926 516017554
// only 8 exact decimals for 500 iterations
// A very very slow convergence.
// Here is a quicker version without any obvious pattern
 
{def pi
{lambda {:n}
{cons {A.get :n {A.new 3 7 15 1 292 1 1 1 2 1 3 1 14 2 1 1}} 1}}}
 
{gcf pi 15}
-> 3.1415926 53589793
 
// Much quicker, 15 exact decimals after 15 iterations
</syntaxhighlight>
 
 
=={{header|Lua}}==
{{trans|C}}
<syntaxhighlight lang="lua">function calc(fa, fb, expansions)
local a = 0.0
local b = 0.0
local r = 0.0
local i = expansions
while i > 0 do
a = fa(i)
b = fb(i)
r = b / (a + r)
i = i - 1
end
a = fa(0)
return a + r
end
 
function sqrt2a(n)
if n ~= 0 then
return 2.0
else
return 1.0
end
end
 
function sqrt2b(n)
return 1.0
end
 
function napiera(n)
if n ~= 0 then
return n
else
return 2.0
end
end
 
function napierb(n)
if n > 1.0 then
return n - 1.0
else
return 1.0
end
end
 
function pia(n)
if n ~= 0 then
return 6.0
else
return 3.0
end
end
 
function pib(n)
local c = 2.0 * n - 1.0
return c * c
end
 
function main()
local sqrt2 = calc(sqrt2a, sqrt2b, 1000)
local napier = calc(napiera, napierb, 1000)
local pi = calc(pia, pib, 1000)
print(sqrt2)
print(napier)
print(pi)
end
 
main()</syntaxhighlight>
{{out}}
<pre>1.4142135623731
2.718281828459
3.1415926533405</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
contfrac:=n->evalf(Value(NumberTheory:-ContinuedFraction(n)));
contfrac(2^(0.5));
contfrac(Pi);
contfrac(exp(1));
</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">sqrt2=Function[n,{1,Transpose@{Array[2&,n],Array[1&,n]}}];
napier=Function[n,{2,Transpose@{Range[n],Prepend[Range[n-1],1]}}];
pi=Function[n,{3,Transpose@{Array[6&,n],Array[(2#-1)^2&,n]}}];
approx=Function[l,
N[Divide@@First@Fold[{{#2.#[[;;,1]],#2.#[[;;,2]]},#[[1]]}&,{{l[[2,1,1]]l[[1]]+l[[2,1,2]],l[[2,1,1]]},{l[[1]],1}},l[[2,2;;]]],10]];
r2=approx/@{sqrt2@#,napier@#,pi@#}&@10000;r2//TableForm</syntaxhighlight>
{{out}}
</lang>
Output:
<pre>
1.414213562
Line 539 ⟶ 2,342:
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">cfeval(x) := block([a, b, n, z], a: x[1], b: x[2], n: length(a), z: 0,
for i from n step -1 thru 2 do z: b[i]/(a[i] + z), a[1] + z)$
 
Line 561 ⟶ 2,364:
fpprec: 20$
x: cfeval(cf_pi(10000))$
bfloat(x - %pi); /* 2.4999999900104930006b-13 */</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight lang="netrexx">/* REXX ***************************************************************
* Derived from REXX ... Derived from PL/I with a little "massage"
* SQRT2= 1.41421356237309505 <- PL/I Result
Line 616 ⟶ 2,419:
end
Get_Coeffs(form,0)
return (a + temp)</langsyntaxhighlight>
Who could help me make a,b,sqrt2,napier,pi global (public) variables?
This would simplify the solution:-)
Line 622 ⟶ 2,425:
I got this help and simplified the program.
 
However, I am told that 'my' value of pi is incorrect. I will investigate!
I will investigate!
 
Apparently the coefficients given in the task description are only good for an approxunationapproximation. One should, therefore, not SHOW more that 15 digits. See http://de.wikipedia.org/wiki/Kreiszahl
One should, therefore, not SHOW more that 15 digits. See http://de.wikipedia.org/wiki/Kreiszahl
 
See [[#REXX|Rexx]] for a better computation
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">proc calc(f: proc(n: int): tuple[a, b: float], n: int): float =
var a, b, temp = 0.0
for i in countdown(n, 1):
(a, b) = f(i)
temp = b / (a + temp)
(a, b) = f(0)
a + temp
 
proc sqrt2(n: int): tuple[a, b: float] =
if n > 0:
(2.0, 1.0)
else:
(1.0, 1.0)
 
proc napier(n: int): tuple[a, b: float] =
let a = if n > 0: float(n) else: 2.0
let b = if n > 1: float(n - 1) else: 1.0
(a, b)
 
proc pi(n: int): tuple[a, b: float] =
let a = if n > 0: 6.0 else: 3.0
let b = (2 * float(n) - 1) * (2 * float(n) - 1)
(a, b)
 
echo calc(sqrt2, 20)
echo calc(napier, 15)
echo calc(pi, 10000)</syntaxhighlight>
{{out}}
<pre>1.414213562373095
2.718281828459046
3.141592653589544</pre>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let pi = 3, fun n -> ((2*n-1)*(2*n-1), 6)
and nap = 2, fun n -> (max 1 (n-1), n)
and root2 = 1, fun n -> (1, 2) in
 
let eval (i,f) k =
let rec frac n =
let a, b = f n in
float a /. (float b +.
if n >= k then 0.0 else frac (n+1)) in
float i +. frac 1 in
 
Printf.printf "sqrt(2)\t= %.15f\n" (eval root2 1000);
Printf.printf "e\t= %.15f\n" (eval nap 1000);
Printf.printf "pi\t= %.15f\n" (eval pi 1000);</syntaxhighlight>
Output (inaccurate due to too few terms):
<pre>sqrt(2) = 1.414213562373095
e = 2.718281828459046
pi = 3.141592653340542</pre>
 
=={{header|PARI/GP}}==
Partial solution for simple continued fractions.
<langsyntaxhighlight lang="parigp">back(v)=my(t=contfracpnqn(v));t[1,1]/t[2,1]*1.
back(vector(100,i,2-(i==1)))</langsyntaxhighlight>
 
Output:
<pre>%1 = 1.4142135623730950488016887242096980786</pre>
 
=={{header|Pascal}}==
This console application is written in Delphi, which allows the results to be displayed to 17 correct decimal places (Free Pascal seems to allow only 16). As in the jq solution, we aim to work forwards and stop as soon the desired precision has been reached, rather than guess a suitable number of terms and work backwards. In this program, the continued fraction is converted to an infinite sum, each term after the first being the difference between consecutive convergents. The convergence for pi is very slow (as others have noted) so as well as the c.f. in the task description an alternative is given from the Wikipedia article "Continued fraction".
<syntaxhighlight lang="pascal">
program ContFrac_console;
 
{$APPTYPE CONSOLE}
 
uses
SysUtils;
 
type TCoeffFunction = function( n : integer) : extended;
 
// Calculate continued fraction as a sum, working forwards.
// Stop on reaching a term with absolute value less than epsilon,
// or on reaching the maximum number of terms.
procedure CalcContFrac( a, b : TCoeffFunction;
epsilon : extended;
maxNrTerms : integer = 1000); // optional, with default
var
n : integer;
sum, term, u, v : extended;
whyStopped : string;
begin
sum := a(0);
term := b(1)/a(1);
v := a(1);
n := 1;
repeat
sum := sum + term;
inc(n);
u := v;
v := a(n) + b(n)/u;
term := -term * b(n)/(u*v);
until (Abs(term) < epsilon) or (n >= maxNrTerms);
if n >= maxNrTerms then whyStopped := 'too many terms'
else whyStopped := 'converged';
WriteLn( SysUtils.Format( '%21.17f after %d terms (%s)',
[sum, n, whyStopped]));
end;
 
//---------------- a and b for sqrt(2) ----------------
function a_sqrt2( n : integer) : extended;
begin
if n = 0 then result := 1
else result := 2;
end;
function b_sqrt2( n : integer) : extended;
begin
result := 1;
end;
 
//---------------- a snd b for e ----------------
function a_e( n : integer) : extended;
begin
if n = 0 then result := 2
else result := n;
end;
function b_e( n : integer) : extended;
begin
if n = 1 then result := 1
else result := n - 1;
end;
 
//-------- Rosetta Code a and b for pi --------
function a_pi( n : integer) : extended;
begin
if n = 0 then result := 3
else result := 6;
end;
function b_pi( n : integer) : extended;
var
temp : extended;
begin
temp := 2*n - 1;
result := temp*temp;
end;
 
//-------- More efficient a and b for pi --------
function a_pi_alt( n : integer) : extended;
begin
if n = 0 then result := 0
else result := 2*n - 1;
end;
function b_pi_alt( n : integer) : extended;
var
temp : extended;
begin
if n = 1 then
result := 4
else begin
temp := n - 1;
result := temp*temp;
end;
end;
 
//---------------- Main routine ----------------
// Unlike Free Pascal, Delphi does not require
// an @ sign before the function names.
begin
WriteLn( 'sqrt(2)');
CalcContFrac( a_sqrt2, b_sqrt2, 1E-20);
WriteLn( 'e');
CalcContFrac( a_e, b_e, 1E-20);
WriteLn( 'pi');
CalcContFrac( a_pi, b_pi, 1E-20);
WriteLn( 'pi (alternative formula)');
CalcContFrac( a_pi_alt, b_pi_alt, 1E-20);
end.
</syntaxhighlight>
{{out}}
<pre>
sqrt(2)
1.41421356237309505 after 27 terms (converged)
e
2.71828182845904524 after 20 terms (converged)
pi
3.14159265383979293 after 1000 terms (too many terms)
pi (alternative formula)
3.14159265358979324 after 29 terms (converged)
</pre>
 
=={{header|Perl}}==
Use closures to implement the infinite lists of coeffficients.
{{trans|Perl6}}
Perl5 does not really support lazy lists but we can use closures to do something similar.
 
<syntaxhighlight lang="perl">use strict;
With a recent version of Perl (5.10 or above), we can also use persistent private variables (see perlsub). We just need to declare this with the 'use feature "state"' pragma.
use warnings;
no warnings 'recursion';
use experimental 'signatures';
 
sub continued_fraction ($a, $b, $n = 100) {
In this example we'll show both methods.
$a->() + ($n and $b->() / continued_fraction($a, $b, $n-1));
}
 
printf "√2 ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ ? 2 : 1 } }, sub { 1 };
<lang perl>sub continued_fraction {
printf "e ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ or 2 } }, do { my $n; sub { $n++ or 1 } };
my ($a, $b, $n) = @_;
printf "π ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ ? 6 : 3 } }, do { my $n; sub { (2*$n++ + 1)**2 } }, 1000;
$n //= 100;
printf "π/2 ≈ %.9f\n", continued_fraction do { my $n; sub { 1/($n++ or 1) } }, sub { 1 }, 1000;</syntaxhighlight>
{{out}}
<pre>√2 ≈ 1.414213562
e ≈ 2.718281828
π ≈ 3.141592653
π/2 ≈ 1.570717797</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">precision</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">10000</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">continued_fraction</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">steps</span><span style="color: #0000FF;">=</span><span style="color: #000000;">precision</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">steps</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">:=</span> <span style="color: #000000;">b</span> <span style="color: #0000FF;">/</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">a</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">sqr2</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?</span><span style="color: #000000;">1</span><span style="color: #0000FF;">:</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">nap</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?</span><span style="color: #000000;">2</span><span style="color: #0000FF;">:</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">?</span><span style="color: #000000;">1</span><span style="color: #0000FF;">:</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)}</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">pi</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?</span><span style="color: #000000;">3</span><span style="color: #0000FF;">:</span><span style="color: #000000;">6</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)}</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Precision: %d\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">precision</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Sqr(2): %.10g\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">continued_fraction</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sqr2</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Napier: %.10g\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">continued_fraction</span><span style="color: #0000FF;">(</span><span style="color: #000000;">nap</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Pi: %.10g\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">continued_fraction</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pi</span><span style="color: #0000FF;">)})</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Precision: 10000
Sqr(2): 1.414213562
Napier: 2.718281828
Pi: 3.141592654
</pre>
 
=={{header|Picat}}==
For Pi a test is added with a higher precision (200 -> 2000) to get a better result.
 
===Recursion===
{{trans|Prolog}}
<syntaxhighlight lang="picat">go =>
 
% square root 2
continued_fraction(200, sqrt_2_ab, V1),
printf("sqrt(2) = %w (diff: %0.15f)\n", V1, V1-sqrt(2)),
 
% napier
continued_fraction(200, napier_ab, V2),
printf("e = %w (diff: %0.15f)\n", V2, V2-math.e),
 
% pi
continued_fraction(200, pi_ab, V3),
printf("pi = %w (diff: %0.15f)\n", V3, V3-math.pi),
% get a better precision
continued_fraction(20000, pi_ab, V3b),
printf("pi = %w (diff: %0.15f)\n", V3b, V3b-math.pi),
nl.
 
continued_fraction(N, Compute_ab, V) ?=>
continued_fraction(N, Compute_ab, 0, V).
continued_fraction(0, Compute_ab, Temp, V) ?=>
my @a = map &$a, 0 .. $n;
call(Compute_ab, 0, A, _),
my @b = map &$b, 1 .. $n;
V = A + Temp.
continued_fraction(N, Compute_ab, Tmp, V) =>
my $x = pop @a;
call(Compute_ab, N, A, B),
$x = pop(@a) + pop(@b)/$x while @a;
Tmp1 = B / (A + Tmp),
return $x;
N1 = N - 1,
}
continued_fraction(N1, Compute_ab, Tmp1, V).
 
% definitions for square root of 2
sqrt_2_ab(0, 1, 1).
sqrt_2_ab(_, 2, 1).
% definitions for napier
# using closures
napier_ab(0, 2, _).
printf "√2 ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ ? 2 : 1 } }, sub { 1 };
napier_ab(1, 1, 1).
napier_ab(N, N, V) :-
V is N - 1.
% definitions for pi
pi_ab(0, 3, _).
pi_ab(N, 6, V) :-
V is (2 * N - 1)*(2 * N - 1).</syntaxhighlight>
 
# using persistent private variables
use feature 'state'
printf "e ≈ %.9f\n", continued_fraction sub { state $n; $n++ ? $n-1 : 2 }, sub { state $n; $n++ ? $n-1 : 1 };
printf "τ ≈ %.9f\n", continued_fraction sub { 6 }, sub { state $n; $n++ ? (2*$n - 1)**2 : 2 }, 1_000;
</lang>
{{out}}
<pre>
<pre>√2 ≈ 1.414213562
sqrt(2) = 1.414213562373095 (diff: 0.000000000000000)
e ≈ 2.718281828
e = 2.718281828459046 (diff: 0.000000000000000)
τ ≈ 6.283185307</pre>
pi = 3.141592622804847 (diff: -0.000000030784946)
pi = 3.141592653589762 (diff: -0.000000000000031)
</pre>
 
===Iterative===
=={{header|Perl 6}}==
{{trans|Python}}
(from Python's Fast Iterative version)
<syntaxhighlight lang="picat">continued_fraction_it(Fun, N) = Ret =>
Temp = 0.0,
foreach(I in N..-1..1)
[A,B] = apply(Fun,I),
Temp := B / (A + Temp)
end,
F = apply(Fun,0),
Ret = F[1] + Temp.
 
fsqrt2(N) = [cond(N > 0, 2, 1),1].
<lang perl6>sub continued-fraction(:@a, :@b, Int :$n = 100)
fnapier(N) = [cond(N > 0, N,2), cond(N>1,N-1,1)].
{
fpi(N) = [cond(N>0,6,3), (2*N-1) ** 2].</syntaxhighlight>
my $x = @a[$n - 1];
$x = @a[$_ - 1] + @b[$_] / $x for reverse 1 ..^ $n;
$x;
}
 
Which has exactly the same output as the recursive version.
printf "√2 ≈ %.9f\n", continued-fraction(:a(1, 2 xx *), :b(*, 1 xx *));
printf "e ≈ %.9f\n", continued-fraction(:a(2, 1 .. *), :b(*, 1, 1 .. *));
printf "π ≈ %.9f\n", continued-fraction(:a(3, 6 xx *), :b(*, [\+] 1, (8, 16 ... *)), :n(1000));</lang>
 
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">(scl 49)
(de fsqrt2 (N A)
(default A 1)
(cond
((> A (inc N)) 2)
(T
(+
(if (=1 A) 1.0 2.0)
(*/ `(* 1.0 1.0) (fsqrt2 N (inc A))) ) ) ) )
(de pi (N A)
(default A 1)
(cond
((> A (inc N)) 6.0)
(T
(+
(if (=1 A) 3.0 6.0)
(*/
(* (** (dec (* 2 A)) 2) 1.0)
1.0
(pi N (inc A)) ) ) ) ) )
(de napier (N A)
(default A 0)
(cond
((> A N) (* A 1.0))
(T
(+
(if (=0 A) 2.0 (* A 1.0))
(*/
(if (> 1 A) 1.0 (* A 1.0))
1.0
(napier N (inc A)) ) ) ) ) )
(prinl (format (fsqrt2 200) *Scl))
(prinl (format (napier 200) *Scl))
(prinl (format (pi 200) *Scl))</syntaxhighlight>
{{out}}
<pre>
<pre>√2 ≈ 1.414213562
1.4142135623730950488016887242096980785696718753770
e ≈ 2.718281828
2.7182818284590452353602874713526624977572470937000
π ≈ 3.141592654</pre>
3.1415926839198062649342019294083175420335002640134
</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight PL/Ilang="pli">/* Version for SQRT(2) */
test: proc options (main);
declare n fixed;
Line 703 ⟶ 2,802:
put (1 + 1/denom(2));
 
end test;</syntaxhighlight>
{{out}}
</lang>
Result:
<pre> 1.41421356237309505E+0000 </pre>
Version for NAPIER:
<syntaxhighlight lang="pli">test: proc options (main);
declare n fixed;
 
Line 720 ⟶ 2,818:
put (2 + 1/denom(0));
 
end test;</langsyntaxhighlight>
<pre> 2.71828182845904524E+0000 </pre>
 
Version for SQRT2, NAPIER, PI
<syntaxhighlight lang="pli">/* Derived from continued fraction in Wiki Ada program */
 
continued_fractions: /* 6 Sept. 2012 */
Line 767 ⟶ 2,864:
put skip edit ('PI=', calc(pi, 99999)) (a(10), f(20,17));
 
end continued_fractions;</syntaxhighlight>
{{out}}
</lang>
Output:
<pre>
SQRT2= 1.41421356237309505
Line 777 ⟶ 2,873:
 
=={{header|Prolog}}==
<langsyntaxhighlight Prologlang="prolog">continued_fraction :-
% square root 2
continued_fraction(200, sqrt_2_ab, V1),
Line 819 ⟶ 2,915:
pi_ab(0, 3, _).
pi_ab(N, 6, V) :-
V is (2 * N - 1)*(2 * N - 1).</syntaxhighlight>
{{out}}
</lang>
Output :
<pre> ?- continued_fraction.
sqrt(2) = 1.4142135623730951
Line 831 ⟶ 2,926:
=={{header|Python}}==
{{works with|Python|2.6+ and 3.x}}
<syntaxhighlight lang="python">from fractions import Fraction
<lang python>
from fractions import Fraction
import itertools
try: zip = itertools.izip
Line 898 ⟶ 2,992:
cf = CF(Pi_a(), Pi_b(), 950)
print(pRes(cf, 10))
#3.1415926532</syntaxhighlight>
</lang>
===Fast iterative version===
{{trans|D}}
<langsyntaxhighlight lang="python">from decimal import Decimal, getcontext
 
def calc(fun, n):
Line 925 ⟶ 3,018:
print calc(fsqrt2, 200)
print calc(fnapier, 200)
print calc(fpi, 200)</langsyntaxhighlight>
{{out}}
<pre>1.4142135623730950488016887242096980785696718753770
2.7182818284590452353602874713526624977572470937000
3.1415926839198062649342019294083175420335002640134</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ $ "bigrat.qky" loadfile ] now!
 
[ 1 min
[ table
[ 1 1 ]
[ 2 1 ] ] do ] is sqrt2 ( n --> n/d )
[ dup 2 min
[ table
[ drop 2 1 ]
[ 1 ]
[ dup 1 - ] ] do ] is napier ( n --> n/d )
 
[ dup 1 min
[ table
[ drop 3 1 ]
[ 2 * 1 - dup *
6 swap ] ] do ] is pi ( n --> n/d )
 
[ ]'[ temp put
0 1
rot times
[ i 1+
temp share do
v+ 1/v ]
0 temp take do v+ ] is cf ( n --> n/d )
 
1000 cf sqrt2 10 point$ echo$ cr
1000 cf napier 10 point$ echo$ cr
1000 cf pi 10 point$ echo$ cr</syntaxhighlight>
 
{{out}}
 
<pre>1.4142135624
2.7136688544
3.1413776152</pre>
 
=={{header|Racket}}==
===Using Doubles===
This version uses standard double precision floating point numbers:
<syntaxhighlight lang="racket">
#lang racket
(define (calc cf n)
(match/values (cf 0)
[(a0 b0)
(+ a0
(for/fold ([t 0.0]) ([i (in-range (+ n 1) 0 -1)])
(match/values (cf i)
[(a b) (/ b (+ a t))])))]))
 
(define (cf-sqrt i) (values (if (> i 0) 2 1) 1))
(define (cf-napier i) (values (if (> i 0) i 2) (if (> i 1) (- i 1) 1)))
(define (cf-pi i) (values (if (> i 0) 6 3) (sqr (- (* 2 i) 1))))
 
(calc cf-sqrt 200)
(calc cf-napier 200)
(calc cf-pi 200)
</syntaxhighlight>
Output:
<syntaxhighlight lang="racket">
1.4142135623730951
2.7182818284590455
3.1415926839198063
</syntaxhighlight>
 
===Version - Using Doubles===
This versions uses big floats (arbitrary precision floating point):
<syntaxhighlight lang="racket">
#lang racket
(require math)
(bf-precision 2048) ; in bits
 
(define (calc cf n)
(match/values (cf 0)
[(a0 b0)
(bf+ (bf a0)
(for/fold ([t (bf 0)]) ([i (in-range (+ n 1) 0 -1)])
(match/values (cf i)
[(a b) (bf/ (bf b) (bf+ (bf a) t))])))]))
(define (cf-sqrt i) (values (if (> i 0) 2 1) 1))
(define (cf-napier i) (values (if (> i 0) i 2) (if (> i 1) (- i 1) 1)))
(define (cf-pi i) (values (if (> i 0) 6 3) (sqr (- (* 2 i) 1))))
(calc cf-sqrt 200)
(calc cf-napier 200)
(calc cf-pi 200)
</syntaxhighlight>
Output:
<syntaxhighlight lang="racket">
(bf #e1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358960036439214262599769155193770031712304888324413327207659690547583107739957489062466508437105234564161085482146113860092820802430986649987683947729823677905101453725898480737256099166805538057375451207262441039818826744940289448489312217214883459060818483750848688583833366310472320771259749181255428309841375829513581694269249380272698662595131575038315461736928338289219865139248048189188905788104310928762952913687232022557677738108337499350045588767581063729)
(bf #e2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170276183860626133138458300075204493382656029760673711320070932870912744374704723624212700454495421842219077173525899689811474120614457405772696521446961165559468253835854362096088934714907384964847142748311021268578658461064714894910680584249490719358138073078291397044213736982988247857479512745588762993966446075)
(bf #e3.14159268391980626493420192940831754203350026401337226640663040854412059241988978103217808449508253393479795573626200366332733859609651462659489470805432281782785922056335606047700127154963266242144951481397480765182268219697420028007903565511884267297358842935537138583640066772149177226656227031792115896439889412205871076985598822285367358003457939603015797225018209619662200081521930463480571130673429337524564941105654923909951299948539893933654293161126559643573974163405197696633200469475250152247413175932572922175467223988860975105100904322239324381097207835036465269418118204894206705789759765527734394105147)
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2015-10-31}}
<syntaxhighlight lang="raku" line>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)));</syntaxhighlight>
{{out}}
<pre>√2 ≈ 1.414213562
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{CF}_3(x) = a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + x}}}</math>
Or, more consistently:
:<math>\mathrm{CF}_3(x) = a_0 + \cfrac{b_0}{a_1 + \cfrac{b_1}{a_2 + \cfrac{b_2}{a_3 + \cfrac{b_3}{x}}}}</math>
Viewed as such, <math>\mathrm{CF}_n(x)</math> could be written recursively:
:<math>\mathrm{CF}_n(x) = \mathrm{CF}_{n-1}(a_n + \frac{b_n}{x})</math>
Or in other words:
:<math>\mathrm{CF}_n= \mathrm{CF}_{n-1}\circ f_n = \mathrm{CF}_{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>
 
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).
<syntaxhighlight lang="raku" line>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];</syntaxhighlight>
{{out}}
<pre>√2 ≈ 1.414213552
e ≈ 2.718281827
π ≈ 3.141592411</pre>
 
=={{header|REXX}}==
===version 1===
The &nbsp; '''cf''' &nbsp; subroutine &nbsp; (for '''C'''ontinued '''F'''ractions) &nbsp; isn't limited to positive integers.
<br>Any form of REXX numbers (negative, exponentiated, decimal fractions) can be used.
<br>Note the use of negative fractions for the &nbsp; <big>'''ß'''</big> &nbsp; terms when computing <big>'''<b>√</b>{{overline| &nbsp; ½ &nbsp;}}'''</big>.
 
There isn't any practical limit for the decimal digits that can be used, although 100k digits would be a bit unwieldy to display.
===Version 1===
The '''CF''' subroutine (for continued fractions) isn't limited to positive integers.
<br>Any form of REXX numbers (negative, exponentiated, decimal fractions) can be used;
<br>[note the use of negative fractions for the ß terms when computing √½].
<br><br>There isn't any practical limit on the precision that can be used, although 100k digits would be a bit unwieldly to display.
<br><br>A generalized '''√''' function was added to calculate a few low integers (and also ½).
<br>In addition, '''½π''' was calculated (as described in the ''talk'' page under ''Gold Credit'').
<br><br>More code is used for nicely formatting the output than the continued fraction calculation.
<lang rexx>/*REXX program calculates and displays values of some specific continued*/
/*───────────── fractions (along with their α and ß terms). */
/*───────────── Continued fractions: also known as anthyphairetic ratio.*/
T=500 /*use 500 terms for calculations.*/
showDig=100; numeric digits 2*showDig /*use 100 digits for the display.*/
a=; @=; b= /*omitted ß terms are assumed = 1*/
/*══════════════════════════════════════════════════════════════════════*/
a=1 rep(2); call tell '√2'
/*══════════════════════════════════════════════════════════════════════*/
a=1 rep(1 2); call tell '√3' /*also: 2∙sin(π/3) */
/*══════════════════════════════════════ ___ ════════════════════════*/
/*generalized √ N */
do N=2 to 11; a=1 rep(2); b=rep(N-1); call tell 'gen √'N; end
N=1/2; a=1 rep(2); b=rep(N-1); call tell 'gen √½'
/*══════════════════════════════════════════════════════════════════════*/
do j=1 for T; a=a j; end; b=1 a; a=2 a; call tell 'e'
/*══════════════════════════════════════════════════════════════════════*/
do j=1 for T by 2; a=a j; b=b j+1; end; call tell '1÷[√e-1]'
/*══════════════════════════════════════════════════════════════════════*/
do j=1 for T; a=a j; end; b=a; a=0 a; call tell '1÷[e-1]'
/*══════════════════════════════════════════════════════════════════════*/
a=1 rep(1); call tell 'φ, phi'
/*══════════════════════════════════════════════════════════════════════*/
a=1; do j=1 for T by 2; a=a j 1; end; call tell 'tan(1)'
/*══════════════════════════════════════════════════════════════════════*/
a=1; do j=1 for T; a=a 2*j+1; end; call tell 'coth(1)'
/*══════════════════════════════════════════════════════════════════════*/
a=2; do j=1 for T; a=a 4*j+2; end; call tell 'coth(½)' /*also: [e+1] ÷ [e-1] */
/*══════════════════════════════════════════════════════════════════════*/
T=10000
a=1 rep(2)
do j=1 for T by 2; b=b j**2; end; call tell '4÷π'
/*══════════════════════════════════════════════════════════════════════*/
T=10000
a=1; do j=1 for T; a=a 1/j; @=@ '1/'j; end; call tell '½π, ½pi'
/*══════════════════════════════════════════════════════════════════════*/
T=10000
a=0 1 rep(2)
do j=1 for T by 2; b=b j**2; end; b=4 b; call tell 'π, pi'
/*══════════════════════════════════════════════════════════════════════*/
T=10000
a=0; do j=1 for T; a=a j*2-1; b=b j**2; end; b=4 b; call tell 'π, pi'
/*══════════════════════════════════════════════════════════════════════*/
T=100000
a=3 rep(6)
do j=1 for T by 2; b=b j**2; end; call tell 'π, pi'
exit /*stick a fork in it, we're done.*/
 
A generalized &nbsp; <big>'''<b>√</b>{{overline| &nbsp;}}'''</big> &nbsp; function was added to calculate a few low integers &nbsp; (and also &nbsp; <big><sup>'''1'''</sup></big>/<big><sub>'''2'''</sub></big>).
/*────────────────────────────────CF subroutine─────────────────────────*/
 
cf: procedure; parse arg C x,y; !=0; numeric digits digits()+5
<!--
do k=words(x) to 1 by -1; a=word(x,k); b=word(word(y,k) 1,1)
In addition, &nbsp; <big><sup>'''1'''</sup></big>/<big><sub>'''2'''</sub> π</big> &nbsp; was calculated (as described in the ''talk'' page under ''Gold Credit'').
d=a+!; if d=0 then call divZero /*in case divisor is bogus.*/
-->
!=b/d /*here's a binary mosh pit.*/
 
end /*k*/
More code is used for nicely formatting the output than the continued fraction calculation.
return !+C
<syntaxhighlight lang="rexx">/*REXX program calculates and displays values of various continued fractions. */
/*────────────────────────────────DIVZERO subroutine────────────────────*/
parse arg terms digs .
divZero: say; say '***error!***'; say 'division by zero.'; say; exit 13
if terms=='' | terms=="," then terms=500
/*────────────────────────────────GETT subroutine───────────────────────*/
if digs=='' | digs=="," then digs=100
getT: parse arg stuff,width,ma,mb,_
numeric digits digs /*use 100 decimal digits for display.*/
do m=1; mm=m+ma; mn=max(1,m-mb); w=word(stuff,m)
b.=1 /*omitted ß terms are assumed to be 1.*/
w=right(w,max(length(word(As,mm)),length(word(Bs,mn)),length(w)))
/*══════════════════════════════════════════════════════════════════════════════════════*/
if length(_ w)>width then leave /*stop getting terms?*/
a.=2; _=_ w /*whole, don call tell 't√2', chop. */cf(1)
/*══════════════════════════════════════════════════════════════════════════════════════*/
end /*m*/ /*done building terms*/
returna.=1; strip(_) do N=2 by 2 to terms; a.N=2; end; call tell '√3', cf(1) /*stripalso: leading blank2∙sin(π/3) */
/*══════════════════════════════════════════════════════════════════════════════════════*/
/*────────────────────────────────REP subroutine────────────────────────*/
rep:a.=2 parse arg rep; return space(copies(' 'rep,/* T%words(rep))) ___ */
do N=2 to 17 /*generalized √ N */
/*────────────────────────────────RF subroutine─────────────────────────*/
b.=N-1; NN=right(N, 2); call tell 'gen √'NN, cf(1)
rf: parse arg xxx,z
end /*N*/
do m=1 for T; w=word(xxx,m) ; if w=='1/1' | w=1 then w=1
/*══════════════════════════════════════════════════════════════════════════════════════*/
if w=='1/2' | w=1/2 then w='½'; if w=-.5 then w='-½'
a.=2; b.=-1/2; if w=='1/4' | w=1/4 then w='¼'; if w=-.25 then w= call tell 'gen √ ½', cf(1)
/*══════════════════════════════════════════════════════════════════════════════════════*/
z=z w
do j=1 for terms; a.j=j; if j>1 then b.j=a.p; p=j; end; call tell 'e', cf(2)
end
/*══════════════════════════════════════════════════════════════════════════════════════*/
return z /*done re-formatting.*/
a.=1; call tell 'φ, phi', cf(1)
/*────────────────────────────────TELL subroutine───────────────────────*/
/*══════════════════════════════════════════════════════════════════════════════════════*/
tell: parse arg ?; v=cf(a,b); numeric digits showdig; As=rf(@ a); Bs=rf(b)
a.=1; do j=1 sayfor right(?,8)terms; if 'j//2 then a.j='j; left(v/1,showdig) ' αend; terms= ' call getTtell 'tan(As1)',72 ,0,cf(1)
/*══════════════════════════════════════════════════════════════════════════════════════*/
if b\=='' then say right('',8+2+showdig+1) ' ß terms= ' getT(Bs,72-2,1,0)
do j=1 for terms; a.j=2*j+1; end; call tell 'coth(1)', cf(1)
a=; @=; b=; return</lang>
/*══════════════════════════════════════════════════════════════════════════════════════*/
do j=1 for terms; a.j=4*j+2; end; call tell 'coth(½)', cf(2) /*also: [e+1]÷[e-1] */
/*══════════════════════════════════════════════════════════════════════════════════════*/
terms=100000
a.=6; do j=1 for terms; b.j=(2*j-1)**2; end; call tell 'π, pi', cf(3)
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
cf: procedure expose a. b. terms; parse arg C; !=0; numeric digits 9+digits()
do k=terms by -1 for terms; d=a.k+!; !=b.k/d
end /*k*/
return !+C
/*──────────────────────────────────────────────────────────────────────────────────────*/
tell: parse arg ?,v; $=left(format(v)/1,1+digits()); w=50 /*50 bytes of terms*/
aT=; do k=1; _=space(aT a.k); if length(_)>w then leave; aT=_; end /*k*/
bT=; do k=1; _=space(bT b.k); if length(_)>w then leave; bT=_; end /*k*/
say right(?,8) "=" $ ' α terms='aT ...
if b.1\==1 then say right("",12+digits()) ' ß terms='bT ...
a=; b.=1; return /*only 50 bytes of α & ß terms ↑ are displayed. */</syntaxhighlight>
'''output'''
<pre>
<pre style="overflow:scroll">
√2 = 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573 α terms= 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2...
√3 = 1.73205080756887729352744634150587236694280525381038062805580697945193301690880003708114618675724857732050807568877293527446341505872366942805253810380628055806979451933016908800037081146186757248576 α terms= 1 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1...
gen √2√ 2 = 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573 α terms= 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2...
gen √ 3 = 1.732050807568877293527446341505872366942805253810380628055806979451933016908800037081146186757248576 α terms=2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ...
ß terms= 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
gen √3 = 1.73205080756887729352744634150587236694280525381038062805580697945193301690880003708114618675724857 α terms= 1 2 2 2 2 2 2 2 2 2 2 ß terms=2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ...
gen 4 = 2 ßα terms= 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2...
gen √4 = 2 α terms= 1 2 2 2 2 2ß 2 2 2 2 2terms=3 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 2...
gen √ 5 = 2.236067977499789696409173668731276235440618359611525724270897245410520925637804899414414408378782275 α terms=2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ...
ß terms= 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
ß terms=4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 ...
gen √5 = 2.23606797749978969640917366873127623544061835961152572427089724541052092563780489941441440837878227 α terms= 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
gen √ 6 = 2.449489742783178098197284074705891391965947480656670128432692567250960377457315026539859433104640235 α terms=2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ...
ß terms= 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
ß terms=5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 ...
gen √6 = 2.44948974278317809819728407470589139196594748065667012843269256725096037745731502653985943310464023 α terms= 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
gen √ 7 = 2.645751311064590590501615753639260425710259183082450180368334459201068823230283627760392886474543611 α terms=2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ...
ß terms= 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
ß terms=6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 ...
gen √7 = 2.64575131106459059050161575363926042571025918308245018036833445920106882323028362776039288647454361 α terms= 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
gen √ 8 = 2.828427124746190097603377448419396157139343750753896146353359475981464956924214077700775068655283145 α terms=2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ...
ß terms= 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
ß terms=7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 ...
gen √8 = 2.82842712474619009760337744841939615713934375075389614635335947598146495692421407770077506865528314 α terms= 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
gen 9 = 3 ßα terms=2 2 2 2 7 7 7 7 7 7 7 7 7 7 7 7 7 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 7...
gen √9 = 3 α terms= 1 2 2 2 2 2ß 2 2 2 2 2terms=8 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 2...
gen √10 = 3.162277660168379331998893544432718533719555139325216826857504852792594438639238221344248108379300295 α terms=2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ...
ß terms= 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
ß terms=9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 ...
gen √10 = 3.16227766016837933199889354443271853371955513932521682685750485279259443863923822134424810837930029 α terms= 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
gen √11 = 3.316624790355399849114932736670686683927088545589353597058682146116484642609043846708843399128290651 α terms=2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ...
ß terms= 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
ß terms=10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 ...
gen √11 = 3.31662479035539984911493273667068668392708854558935359705868214611648464260904384670884339912829065 α terms= 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
gen √12 = 3.464101615137754587054892683011744733885610507620761256111613958903866033817600074162292373514497151 α terms=2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ...
ß terms= 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
ß terms=11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 ...
gen √½ = 0.70710678118654752440084436210484903928483593768847403658833986899536623923105351942519376716382078 α terms= 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
gen √13 = 3.605551275463989293119221267470495946251296573845246212710453056227166948293010445204619082018490718 α terms=2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ...
ß terms= -½ -½ -½ -½ -½ -½ -½ -½ -½ -½ -½ -½ -½ -½ -½ -½ -½ -½ -½ -½ -½ -½ -½
ß terms=12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 ...
e = 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642 α terms= 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
gen √14 = 3.741657386773941385583748732316549301756019807778726946303745467320035156306939027976809895194379572 α terms=2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ...
ß terms= 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
ß terms=13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 ...
1÷[√e-1] = 1.54149408253679828413110344447251463834045923684188210947413695663754263914331480707182572408500774 α terms= 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
gen √15 = 3.872983346207416885179265399782399610832921705291590826587573766113483091936979033519287376858673518 α terms=2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ...
ß terms= 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48
ß terms=14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 ...
1÷[e-1] = 0.58197670686932642438500200510901155854686930107539613626678705964804381739166974328720470940487505 α terms= 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
gen √16 = 4 ßα terms=2 2 2 2 12 2 32 42 52 62 72 82 92 102 112 122 132 142 152 162 172 182 192 202 21 22 23 24 252 26...
ß terms=15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 ...
φ, phi = 1.61803398874989484820458683436563811772030917980576286213544862270526046281890244970720720418939113 α terms= 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
gen tan(1)√17 = 14.55740772465490223050697480745836017308725077238152003838394660569886139715172728955509996520224298123105625617660549821409855974077025147199225373620434398633573094954346337621593587863650810684297 α terms=2 2 12 12 12 32 12 52 12 72 12 92 12 112 12 132 12 152 12 172 12 192 12 212 12 23 1 25 1 27 1 29 1...
ß terms=16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 ...
coth(1) = 1.31303528549933130363616124693084783291201394124045265554315296756708427046187438267467924148085630 α terms= 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
coth(gen √ ½) = 20.16395341373865284877000401021802311709373860215079227253357411929608763478333948657440941880975011707106781186547524400844362104849039284835937688474036588339868995366239231053519425193767163820786 α terms=2 2 2 62 102 142 182 222 262 302 342 382 422 462 502 542 582 622 662 702 742 782 822 862 902 94...
4÷π = 1.27283479368898552763028955877501991659132774562422849516943825241995907438793488819711543252100078 α terms= 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ß terms=-0.5 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5 ...
e = 2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427 α terms=1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...
ß terms= 1 9 25 49 81 121 169 225 289 361 441 529 625 729 841 961 1089 1225
½π φ, ½piphi = 1.57071779679495409624134340842172803914665374867756685353559415360226497865248110814032818773478787618033988749894848204586834365638117720309179805762862135448622705260462818902449707207204189391137 α terms=1 1 1 ½1 1/3 ¼1 1/5 1/6 1/7 1/8 1/9 1/10 1/11 1/12 1/13 1/14 1/15 1/16 1/17 1 1 1 1 1 1 ...
tan(1) = 1.557407724654902230506974807458360173087250772381520038383946605698861397151727289555099965202242984 α terms=1 1 3 1 5 1 7 1 9 1 11 1 13 1 15 1 17 1 19 1 21 1 ...
π, pi = 3.14259165433954305090112773725220456615353825631695587367530386050342717161955770321769607013860474 α terms= 0 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
coth(1) = 1.313035285499331303636161246930847832912013941240452655543152967567084270461874382674679241480856303 α terms=3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 ...
ß terms= 4 1 9 25 49 81 121 169 225 289 361 441 529 625 729 841 961 1089 1225
coth(½) = 2.163953413738652848770004010218023117093738602150792272533574119296087634783339486574409418809750115 α terms=6 10 14 18 22 26 30 34 38 42 46 50 54 58 62 66 70 ...
π, pi = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706 α terms= 0 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41
π, pi = 3.141592653589792988470143264530440384041017830472772036746332303472711537960073664096818977224037083 α terms=6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 ...
ß terms= 4 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400
π, pi = 3.14159265358979298847014326453044038404101783047277203674633230347271153796007366409681897722403708 α terms= 3 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
ß terms= 1 9 25 49 81 121 169 225 289 361 441 529 625 729 841 961 1089 1225
</pre>
Note: &nbsp; even with 200 digit accuracy and 100,000 terms, the last calculation of π (pi) is only accurate to 15 digits.
<br><br>
 
===Versionversion 2 derived from [[#PL/I|PL/I]]===
<langsyntaxhighlight lang="rexx">/* REXX **************************************************************
* Derived from PL/I with a little "massage"
* SQRT2= 1.41421356237309505 <- PL/I Result
Line 1,114 ⟶ 3,310:
end
call Get_Coeffs form, 0
return (A + Temp)</langsyntaxhighlight>
 
===Version 3 better approximation===
 
===version 3 better approximation===
<lang rexx>/* REXX *************************************************************
<syntaxhighlight lang="rexx">/* REXX *************************************************************
* The task description specifies a continued fraction for pi
* that gives a reasonable approximation.
Line 1,189 ⟶ 3,384:
end
call Get_Coeffs 0
return (A + Temp)</langsyntaxhighlight>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Continued fraction
 
see "SQR(2) = " + contfrac(1, 1, "2", "1") + nl
see " e = " + contfrac(2, 1, "n", "n") + nl
see " PI = " + contfrac(3, 1, "6", "(2*n+1)^2") + nl
 
func contfrac(a0, b1, a, b)
expr = ""
n = 0
while len(expr) < (700 - n)
n = n + 1
eval("temp1=" + a)
eval("temp2=" + b)
expr = expr + string(temp1) + char(43) + string(temp2) + "/("
end
str = copy(")",n)
eval("temp3=" + expr + "1" + str)
return a0 + b1 / temp3
</syntaxhighlight>
Output:
<pre>
SQR(2) = 1.414213562373095
e = 2.718281828459046
PI = 3.141592653588017
</pre>
 
=={{header|RPL}}==
This task demonstrates how both global and local variables, arithmetic expressions and stack can be used together to build a compact and versatile piece of code.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
4 ROLL ROT → an bn
≪ 'N' STO 0 '''WHILE''' N 2 ≥ '''REPEAT'''
an + INV bn * EVAL
'N' 1 STO- '''END'''
an + / + EVAL
'N' PURGE
≫ ≫ ‘'''→CFRAC'''’ STO
|
'''→CFRAC''' ''( a0 an b1 bn N -- x ) ''
Unstack an and bn
Loop from N to 2
Calculate Nth fraction
Decrement counter
Calculate last fraction with b1 in stack, then add a0
Discard N variable - not mandatory but hygienic
|}
{{in}}
<pre>
1 2 1 1 100 →CFRAC
2 'N' 1 'N-1' 100 →CFRAC
3 6 1 '(2*N-1)^2' 1000 →CFRAC
1 1 1 1 100 →CFRAC
1 '2-MOD(N,2)' 1 1 100 →CFRAC
</pre>
{{out}}
<pre>
5: 1.41421356237
4: 2.71828182846
3: 3.14159265334
2: 1.61803398875
1: 1.73205080757
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'bigdecimal'
 
# square root of 2
Line 1,238 ⟶ 3,504:
puts estimate(sqrt2, 50).to_s('F')
puts estimate(napier, 50).to_s('F')
puts estimate(pi, 10).to_s('F')</langsyntaxhighlight>
 
{{out}}
<pre>$ ruby cfrac.rb
Line 1,245 ⟶ 3,510:
2.71828182845904523536028747135266249775724709369996
3.1415926536</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
use std::iter;
 
// Calculating a continued fraction is quite easy with iterators, however
// writing a proper iterator adapter is less so. We settle for a macro which
// for most purposes works well enough.
//
// One limitation with this iterator based approach is that we cannot reverse
// input iterators since they are not usually DoubleEnded. To circumvent this
// we can collect the elements and then reverse them, however this isn't ideal
// as we now have to store elements equal to the number of iterations.
//
// Another is that iterators cannot be resused once consumed, so it is often
// required to make many clones of iterators.
macro_rules! continued_fraction {
($a:expr, $b:expr ; $iterations:expr) => (
($a).zip($b)
.take($iterations)
.collect::<Vec<_>>().iter()
.rev()
.fold(0 as f64, |acc: f64, &(x, y)| {
x as f64 + (y as f64 / acc)
})
);
 
($a:expr, $b:expr) => (continued_fraction!($a, $b ; 1000));
}
 
fn main() {
// Sqrt(2)
let sqrt2a = (1..2).chain(iter::repeat(2));
let sqrt2b = iter::repeat(1);
println!("{}", continued_fraction!(sqrt2a, sqrt2b));
 
 
// Napier's Constant
let napiera = (2..3).chain(1..);
let napierb = (1..2).chain(1..);
println!("{}", continued_fraction!(napiera, napierb));
 
 
// Pi
let pia = (3..4).chain(iter::repeat(6));
let pib = (1i64..).map(|x| (2 * x - 1).pow(2));
println!("{}", continued_fraction!(pia, pib));
}
</syntaxhighlight>
 
{{out}}
<pre>
1.4142135623730951
2.7182818284590455
3.141592653339042
</pre>
 
=={{header|Scala}}==
{{works with|Scala|2.9.1}}
Note that Scala-BigDecimal provides a precision of 34 digits. Therefore we take a limitation of 32 digits to avoiding rounding problems.
<langsyntaxhighlight Scalalang="scala">object CF extends App {
import Stream._
val sqrt2 = 1 #:: from(2,0) zip from(1,0)
Line 1,279 ⟶ 3,600:
println()
}
}</langsyntaxhighlight>
{{out}}
Output:
<pre>sqrt2:
ref value: 1.41421356237309504880168872420969
Line 1,296 ⟶ 3,617:
precision: 3.14159265358</pre>
For higher accuracy of pi we have to take more iterations. Unfortunately the foldRight function in calc isn't tail recursiv - therefore a stack overflow exception will be thrown for higher numbers of iteration, thus we have to implement an iterative way for calculation:
<langsyntaxhighlight Scalalang="scala">object CFI extends App {
import Stream._
val sqrt2 = 1 #:: from(2,0) zip from(1,0)
Line 1,330 ⟶ 3,651:
println()
}
}</langsyntaxhighlight>
{{out}}
Output:
<pre>sqrt2:
ref value: 1.41421356237309504880168872420969
Line 1,346 ⟶ 3,667:
cf value: 3.14159265358983426214354599901745
precision: 3.141592653589</pre>
 
=={{header|Scheme}}==
The following code relies on a library implementing SRFI 41 (lazy streams). Most Scheme interpreters include an implementation.
 
<syntaxhighlight lang="scheme">#!r6rs
(import (rnrs base (6))
(srfi :41 streams))
 
(define nats (stream-cons 0 (stream-map (lambda (x) (+ x 1)) nats)))
 
(define (build-stream fn) (stream-map fn nats))
 
(define (stream-cycle s . S)
(cond
((stream-null? (car S)) stream-null)
(else (stream-cons (stream-car s)
(apply stream-cycle (append S (list (stream-cdr s))))))))
 
(define (cf-floor cf) (stream-car cf))
(define (cf-num cf) (stream-car (stream-cdr cf)))
(define (cf-denom cf) (stream-cdr (stream-cdr cf)))
 
(define (cf-integer? x) (stream-null? (stream-cdr x)))
 
(define (cf->real x)
(let refine ((x x) (n 65536))
(cond
((= n 0) +inf.0)
((cf-integer? x) (cf-floor x))
(else (+ (cf-floor x)
(/ (cf-num x)
(refine (cf-denom x) (- n 1))))))))
 
(define (real->cf x)
(let-values (((integer-part fractional-part) (div-and-mod x 1)))
(if (= fractional-part 0.0)
(stream (exact integer-part))
(stream-cons
(exact integer-part)
(stream-cons
1
(real->cf (/ fractional-part)))))))
 
 
(define sqrt2 (stream-cons 1 (stream-constant 1 2)))
 
(define napier
(stream-append (stream 2 1)
(stream-cycle (stream-cdr nats) (stream-cdr nats))))
 
(define pi
(stream-cons 3
(stream-cycle (build-stream (lambda (n) (expt (- (* 2 (+ n 1)) 1) 2)))
(stream-constant 6))))</syntaxhighlight>
 
Test:
<syntaxhighlight lang="scheme">> (cf->real sqrt2)
1.4142135623730951
> (cf->real napier)
2.7182818284590455
> (cf->real pi)
3.141592653589794</syntaxhighlight>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func continued_fraction(a, b, f, n = 1000, r = 1) {
f(func (r) {
r < n ? (a(r) / (b(r) + __FUNC__(r+1))) : 0
}(r))
}
 
var params = Hash(
"φ" => [ { 1 }, { 1 }, { 1 + _ } ],
"√2" => [ { 1 }, { 2 }, { 1 + _ } ],
"e" => [ { _ }, { _ }, { 1 + 1/_ } ],
"π" => [ { (2*_ - 1)**2 }, { 6 }, { 3 + _ } ],
"τ" => [ { _**2 }, { 2*_ + 1 }, { 8 / (1 + _) } ],
)
 
for k in (params.keys.sort) {
printf("%2s ≈ %s\n", k, continued_fraction(params{k}...))
}</syntaxhighlight>
{{out}}
<pre>
e ≈ 2.7182818284590452353602874713526624977572470937
π ≈ 3.14159265383979292596359650286939597045138933078
τ ≈ 6.28318530717958647692528676655900576839433879875
φ ≈ 1.61803398874989484820458683436563811772030917981
√2 ≈ 1.41421356237309504880168872420969807856967187538
</pre>
 
=={{header|Swift}}==
 
{{trans|Rust}}
 
<syntaxhighlight lang="swift">extension BinaryInteger {
@inlinable
public func power(_ n: Self) -> Self {
return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *)
}
}
 
public struct CycledSequence<WrappedSequence: Sequence> {
private var seq: WrappedSequence
private var iter: WrappedSequence.Iterator
 
init(seq: WrappedSequence) {
self.seq = seq
self.iter = seq.makeIterator()
}
}
 
extension CycledSequence: Sequence, IteratorProtocol {
public mutating func next() -> WrappedSequence.Element? {
if let ele = iter.next() {
return ele
} else {
iter = seq.makeIterator()
 
return iter.next()
}
}
}
 
extension Sequence {
public func cycled() -> CycledSequence<Self> {
return CycledSequence(seq: self)
}
}
 
public struct ChainedSequence<Element> {
private var sequences: [AnySequence<Element>]
private var iter: AnyIterator<Element>
private var curSeq = 0
 
init(chain: ChainedSequence) {
self.sequences = chain.sequences
self.iter = chain.iter
self.curSeq = chain.curSeq
}
 
init<Seq: Sequence>(_ seq: Seq) where Seq.Element == Element {
sequences = [AnySequence(seq)]
iter = sequences[curSeq].makeIterator()
}
 
func chained<Seq: Sequence>(with seq: Seq) -> ChainedSequence where Seq.Element == Element {
var res = ChainedSequence(chain: self)
 
res.sequences.append(AnySequence(seq))
 
return res
}
}
 
extension ChainedSequence: Sequence, IteratorProtocol {
public mutating func next() -> Element? {
if let el = iter.next() {
return el
}
 
curSeq += 1
 
guard curSeq != sequences.endIndex else {
return nil
}
 
iter = sequences[curSeq].makeIterator()
 
return iter.next()
}
}
 
extension Sequence {
public func chained<Seq: Sequence>(with other: Seq) -> ChainedSequence<Element> where Seq.Element == Element {
return ChainedSequence(self).chained(with: other)
}
}
 
func continuedFraction<T: Sequence, V: Sequence>(
_ seq1: T,
_ seq2: V,
iterations: Int = 1000
) -> Double where T.Element: BinaryInteger, T.Element == V.Element {
return zip(seq1, seq2).prefix(iterations).reversed().reduce(0.0, { Double($1.0) + (Double($1.1) / $0) })
}
 
let sqrtA = [1].chained(with: [2].cycled())
let sqrtB = [1].cycled()
 
print("√2 ≈ \(continuedFraction(sqrtA, sqrtB))")
 
let napierA = [2].chained(with: 1...)
let napierB = [1].chained(with: 1...)
 
print("e ≈ \(continuedFraction(napierA, napierB))")
 
let piA = [3].chained(with: [6].cycled())
let piB = (1...).lazy.map({ (2 * $0 - 1).power(2) })
 
print("π ≈ \(continuedFraction(piA, piB))")
</syntaxhighlight>
 
{{out}}
 
<pre>√2 ≈ 1.4142135623730951
e ≈ 2.7182818284590455
π ≈ 3.141592653339042</pre>
 
{{trans|Java}}
 
<syntaxhighlight lang="swift">
import Foundation
 
func calculate(n: Int, operation: (Int) -> [Int])-> Double {
var tmp: Double = 0
for ni in stride(from: n, to:0, by: -1) {
var p = operation(ni)
tmp = Double(p[1])/(Double(p[0]) + tmp);
}
return Double(operation(0)[0]) + tmp;
}
 
func sqrt (n: Int) -> [Int] {
return [n > 0 ? 2 : 1, 1]
}
 
func napier (n: Int) -> [Int] {
var res = [n > 0 ? n : 2, n > 1 ? (n - 1) : 1]
return res
}
 
func pi(n: Int) -> [Int] {
var res = [n > 0 ? 6 : 3, Int(pow(Double(2 * n - 1), 2))]
return res
}
print (calculate(n: 200, operation: sqrt));
print (calculate(n: 200, operation: napier));
print (calculate(n: 200, operation: pi));
 
</syntaxhighlight>
 
=={{header|Tcl}}==
Line 1,351 ⟶ 3,912:
{{trans|Python}}
Note that Tcl does not provide arbitrary precision floating point numbers by default, so all result computations are done with IEEE <code>double</code>s.
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
# Term generators; yield list of pairs
Line 1,391 ⟶ 3,952:
puts [cf r2]
puts [cf e]
puts [cf pi 250]; # Converges more slowly</langsyntaxhighlight>
{{out}}
<pre>1.4142135623730951
2.7182818284590455
3.1415926373965735</pre>
 
=={{header|VBA}}==
{{trans|Phix}}<syntaxhighlight lang="vb">Public Const precision = 10000
Private Function continued_fraction(steps As Integer, rid_a As String, rid_b As String) As Double
Dim res As Double
res = 0
For n = steps To 1 Step -1
res = Application.Run(rid_b, n) / (Application.Run(rid_a, n) + res)
Next n
continued_fraction = Application.Run(rid_a, 0) + res
End Function
Function sqr2_a(n As Integer) As Integer
sqr2_a = IIf(n = 0, 1, 2)
End Function
 
Function sqr2_b(n As Integer) As Integer
sqr2_b = 1
End Function
Function nap_a(n As Integer) As Integer
nap_a = IIf(n = 0, 2, n)
End Function
 
Function nap_b(n As Integer) As Integer
nap_b = IIf(n = 1, 1, n - 1)
End Function
Function pi_a(n As Integer) As Integer
pi_a = IIf(n = 0, 3, 6)
End Function
 
Function pi_b(n As Integer) As Long
pi_b = IIf(n = 1, 1, (2 * n - 1) ^ 2)
End Function
 
Public Sub main()
Debug.Print "Precision:", precision
Debug.Print "Sqr(2):", continued_fraction(precision, "sqr2_a", "sqr2_b")
Debug.Print "Napier:", continued_fraction(precision, "nap_a", "nap_b")
Debug.Print "Pi:", continued_fraction(precision, "pi_a", "pi_b")
End Sub</syntaxhighlight>{{out}}
<pre>Precision: 10000
Sqr(2): 1,4142135623731
Napier: 2,71828182845905
Pi: 3,14159265358954 </pre>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Module Module1
Function Calc(f As Func(Of Integer, Integer()), n As Integer) As Double
Dim temp = 0.0
For ni = n To 1 Step -1
Dim p = f(ni)
temp = p(1) / (p(0) + temp)
Next
Return f(0)(0) + temp
End Function
 
Sub Main()
Dim fList = {
Function(n As Integer) New Integer() {If(n > 0, 2, 1), 1},
Function(n As Integer) New Integer() {If(n > 0, n, 2), If(n > 1, n - 1, 1)},
Function(n As Integer) New Integer() {If(n > 0, 6, 3), Math.Pow(2 * n - 1, 2)}
}
 
For Each f In fList
Console.WriteLine(Calc(f, 200))
Next
End Sub
 
End Module</syntaxhighlight>
{{out}}
<pre>1.4142135623731
2.71828182845905
3.14159262280485</pre>
 
=={{header|Wren}}==
{{trans|D}}
<syntaxhighlight lang="wren">var calc = Fn.new { |f, n|
var t = 0
for (i in n..1) {
var p = f.call(i)
t = p[1] / (p[0] + t)
}
return f.call(0)[0] + t
}
 
var pList = [
["sqrt(2)", Fn.new { |n| [(n > 0) ? 2 : 1, 1] }],
["e ", Fn.new { |n| [(n > 0) ? n : 2, (n > 1) ? n - 1 : 1] }],
["pi ", Fn.new { |n| [(n > 0) ? 6 : 3, (2*n - 1) * (2*n - 1)] }]
]
for (p in pList) System.print("%(p[0]) = %(calc.call(p[1], 200))")</syntaxhighlight>
 
{{out}}
<pre>
sqrt(2) = 1.4142135623731
e = 2.718281828459
pi = 3.1415926228048
</pre>
 
=={{header|XPL0}}==
The number of iterations (N) needed to get the 13 digits of accuracy was determined by experiment.
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int N;
real A, B, F;
Line 1,423 ⟶ 4,085:
RlOut(0, 3.0+F); CrLf(0);
RlOut(0, ACos(-1.0)); CrLf(0);
]</langsyntaxhighlight>
{{out}}
 
Output:
<pre>
16
Line 1,437 ⟶ 4,098:
3.141592653589790
</pre>
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">fcn cf(fa,fb,a0){fcn(fa,fb,a0,n){
a0 + [n..1,-1].reduce(
'wrap(p,n){ fb(n)/(fa(n)+p) },0.0) }.fp(fa,fb,a0)
}</syntaxhighlight>
cf creates a function that calculates the continued fraction from the bottom up. The new function takes a single parameter, n, which is used to calculate the nth term.
<syntaxhighlight lang="zkl">sqrt2:=cf((2.0).noop,(1.0).noop,1.0);
sqrt2(200) : "%.20e".fmt(_).println();
nap:=cf((0.0).create,fcn(n){ (n==1) and 1.0 or (n-1).toFloat() },2.0);
println(nap(15) - (1.0).e);
pi:=cf((6.0).noop,fcn(n){ n=2*n-1; (n*n).toFloat() },3.0);
println(pi(1000) - (1.0).pi);</syntaxhighlight>
(1.0).create(n) --> n, (1.0).noop(n) --> 1.0
{{out}}
<pre>
1.41421356237309514547e+00
1.33227e-15
-2.49251e-10
</pre>
 
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<syntaxhighlight lang="zxbasic">10 LET a0=1: LET b1=1: LET a$="2": LET b$="1": PRINT "SQR(2) = ";: GO SUB 1000
20 LET a0=2: LET b1=1: LET a$="N": LET b$="N": PRINT "e = ";: GO SUB 1000
30 LET a0=3: LET b1=1: LET a$="6": LET b$="(2*N+1)^2": PRINT "PI = ";: GO SUB 1000
100 STOP
1000 LET n=0: LET e$="": LET p$=""
1010 LET n=n+1
1020 LET e$=e$+STR$ VAL a$+"+"+STR$ VAL b$+"/("
1030 IF LEN e$<(4000-n) THEN GO TO 1010
1035 FOR i=1 TO n: LET p$=p$+")": NEXT i
1040 PRINT a0+b1/VAL (e$+"1"+p$)
1050 RETURN</syntaxhighlight>
2,120

edits