Continued fraction: Difference between revisions

m
m (→‎{{header|Haskell}}: Specified imports, applied hlint hindent. Minor tidying.)
 
(40 intermediate revisions by 22 users not shown)
Line 23:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F calc(f_a, f_b, =n = 1000)
V r = 0.0
L n > 0
Line 32:
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))</langsyntaxhighlight>
 
=={{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}}==
Line 38 ⟶ 155:
 
Generic function for estimating continued fractions:
<langsyntaxhighlight Adalang="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 (Steps : in Natural) return Scalar;</langsyntaxhighlight>
 
<langsyntaxhighlight Adalang="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))));
Line 55 ⟶ 172:
end loop;
return A (0) + Fraction;
end Continued_Fraction;</langsyntaxhighlight>
Test program using the function above to estimate the square root of 2, Napiers constant and pi:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
with Continued_Fraction;
Line 91 ⟶ 208:
Put (Napiers_Constant.Estimate (200), Exp => 0); New_Line;
Put (Pi.Estimate (10000), Exp => 0); New_Line;
end Test_Continued_Fractions;</langsyntaxhighlight>
===Using only Ada 95 features===
This example is exactly the same as the preceding one, but implemented using only Ada 95 features.
<langsyntaxhighlight Adalang="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;</langsyntaxhighlight>
 
<langsyntaxhighlight Adalang="ada">function Continued_Fraction_Ada95 (Steps : in Natural) return Scalar is
function A (N : in Natural) return Scalar is
begin
Line 118 ⟶ 235:
end loop;
return A (0) + Fraction;
end Continued_Fraction_Ada95;</langsyntaxhighlight>
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
with Continued_Fraction_Ada95;
Line 205 ⟶ 322:
Put (Napiers_Constant.Estimate (200), Exp => 0); New_Line;
Put (Pi.Estimate (10000), Exp => 0); New_Line;
end Test_Continued_Fractions_Ada95;</langsyntaxhighlight>
{{out}}
<pre> 1.41421356237310
Line 213 ⟶ 330:
=={{header|ALGOL 68}}==
{{works with|Algol 68 Genie|2.8}}
<syntaxhighlight lang="algol68">
<lang ALGOL68>
PROC cf = (INT steps, PROC (INT) INT a, PROC (INT) INT b) REAL:
BEGIN
Line 239 ⟶ 356:
print (("Napier: ", cf(precision, anap, bnap), newline));
print (("Pi: ", cf(precision, api, bpi)))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 247 ⟶ 364:
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:
<langsyntaxhighlight ATSlang="ats">#include
"share/atspre_staload.hats"
//
Line 319 ⟶ 475:
println! ("napier = ", calc(napier, 100));
println! (" pi = ", calc( pi , 100));
) (* end of [main0] *)</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">sqrt2_a(n) ; function definition is as simple as that
{
return n?2.0:1.0
Line 368 ⟶ 524:
}
 
Msgbox, % "sqrt 2 = " . calc("sqrt2", 1000) . "`ne = " . calc("napier", 1000) . "`npi = " . calc("pi", 1000)</langsyntaxhighlight>
Output with Autohotkey v1 (currently 1.1.16.05):
<langsyntaxhighlight AutoHotkeylang="autohotkey">sqrt 2 = 1.414214
e = 2.718282
pi = 3.141593</langsyntaxhighlight>
Output with Autohotkey v2 (currently alpha 56):
<langsyntaxhighlight AutoHotkeylang="autohotkey">sqrt 2 = 1.4142135623730951
e = 2.7182818284590455
pi = 3.1415926533405418</langsyntaxhighlight>
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 392 ⟶ 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:
<langsyntaxhighlight Axiomlang="axiom">cf(initial, a, b, n) ==
n=1 => initial
temp := 0
Line 404 ⟶ 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 423 ⟶ 579:
expr$ += STR$(EVAL(a$)) + "+" + STR$(EVAL(b$)) + "/("
UNTIL LEN(expr$) > (65500 - N)
= a0 + b1 / EVAL (expr$ + "1" + STRING$(N, ")"))</langsyntaxhighlight>
{{out}}
<pre>
Line 433 ⟶ 589:
=={{header|C}}==
{{works with|ANSI C}}
<langsyntaxhighlight lang="c">/* calculate approximations for continued fractions */
#include <stdio.h>
 
Line 503 ⟶ 659:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> 1.414213562
Line 511 ⟶ 667:
=={{header|C sharp|C#}}==
{{trans|Java}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 536 ⟶ 692:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>1.4142135623731
Line 543 ⟶ 699:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <tuple>
Line 584 ⟶ 740:
<< calc(pi, 10000) << '\n'
<< std::setprecision(old_prec); // reset precision
}</langsyntaxhighlight>
{{out}}
<pre>
Line 595 ⟶ 751:
 
Functions don't take other functions as arguments, so I wrapped them in a dummy record each.
<langsyntaxhighlight lang="chapel">proc calc(f, n) {
var r = 0.0;
 
Line 629 ⟶ 785:
writeln(calc(new Sqrt2(), n));
writeln(calc(new Napier(), n));
writeln(calc(new Pi(), n));</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(defn cfrac
[a b n]
Line 641 ⟶ 797:
(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>
</lang>
{{out}}
<pre>
Line 653 ⟶ 809:
{{works with|GnuCOBOL}}
 
<langsyntaxhighlight COBOLlang="cobol"> identification division.
program-id. show-continued-fractions.
 
Line 838 ⟶ 994:
goback.
end program pi-beta.
</syntaxhighlight>
</lang>
 
{{out}}
Line 847 ⟶ 1,003:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript"># Compute a continuous fraction of the form
# a0 + b1 / (a1 + b2 / (a2 + b3 / ...
continuous_fraction = (f) ->
Line 881 ⟶ 1,037:
x = 2*n - 1
x * x
p Math.PI, continuous_fraction(fpi)</langsyntaxhighlight>
{{out}}
<pre>
Line 898 ⟶ 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 921 ⟶ 1,077:
(* (1- (* 2 n))
(1- (* 2 n))))) 10000)
'double-float))</langsyntaxhighlight>
{{out}}
<pre>sqrt(2) = 1.4142135623730947d0
Line 928 ⟶ 1,084:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.functional, std.traits;
 
FP calc(FP, F)(in F fun, in int n) pure nothrow if (isCallable!F) {
Line 958 ⟶ 1,114:
calc!real(&fNapier, 200).print;
calc!real(&fPi, 200).print;
}</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight lang="erlang">
-module(continued).
-compile([export_all]).
Line 1,009 ⟶ 1,275:
test_nappier (N) ->
continued_fraction(fun nappier_a/1,fun nappier_b/1,N).
</syntaxhighlight>
</lang>
 
{{out}}
<langsyntaxhighlight lang="erlang">
29> continued:test_pi(1000).
3.141592653340542
Line 1,019 ⟶ 1,285:
31> continued:test_nappier(1000).
2.7182818284590455
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
===The Functions===
<langsyntaxhighlight lang="fsharp">
// I provide four functions:-
// cf2S general purpose continued fraction to sequence of float approximations
Line 1,035 ⟶ 1,301:
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>
</lang>
===The Tasks===
<langsyntaxhighlight 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>
</lang>
{{out}}
<pre>
Line 1,052 ⟶ 1,318:
1.41421355164605 < √2 < 1.41421362489487
</pre>
<langsyntaxhighlight lang="fsharp">
cfSqRt 0.25M |> Seq.take 30 |> Seq.iter (printfn "%1.14f")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,088 ⟶ 1,354:
0.50000000000000
</pre>
<langsyntaxhighlight 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>
</lang>
{{out}}
<pre>
Line 1,105 ⟶ 1,371:
3.14140671849650 < π < 3.14183961892940
</pre>
<langsyntaxhighlight 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>
</lang>
{{out}}
<pre>
Line 1,121 ⟶ 1,387:
3.14159265358939 < π < 3.14159265359140
</pre>
<langsyntaxhighlight 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>
</lang>
{{out}}
<pre>
Line 1,137 ⟶ 1,403:
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.
<langsyntaxhighlight lang="factor">USING: arrays combinators io kernel locals math math.functions
math.ranges prettyprint sequences ;
IN: rosetta.cfrac
Line 1,203 ⟶ 1,488:
PRIVATE>
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre> Square root of 2: 1.414213562373095048801688724209
Line 1,210 ⟶ 1,495:
 
=={{header|Felix}}==
<langsyntaxhighlight 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
Line 1,236 ⟶ 1,521:
println$ cf_iter 200 sqrt_2; // => 1.41421
println$ cf_iter 200 napier; // => 2.71818
println$ cf_iter 1000 pi; // => 3.14159</langsyntaxhighlight>
 
=={{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 1,248 ⟶ 1,533:
do i over execute frot f+ f/ -1 +loop
0 swap execute fnip f+ \ calcucate for 0
;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,260 ⟶ 1,545:
 
=={{header|Fortran}}==
<langsyntaxhighlight Fortranlang="fortran">module continued_fractions
implicit none
Line 1,358 ⟶ 1,643:
end function
 
end program examples</langsyntaxhighlight>
{{out}}
<pre>
Line 1,367 ⟶ 1,652:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">#define MAX 70000
 
function sqrt2_a( n as uinteger ) as uinteger
Line 1,404 ⟶ 1,689:
print calc_contfrac( @sqrt2_a, @sqrt2_b, MAX )
print calc_contfrac( @napi_a, @napi_b, MAX )
print calc_contfrac( @pi_a, @pi_b, MAX )</langsyntaxhighlight>
 
=={{header|Fōrmulæ}}==
 
In [http{{FormulaeEntry|page=https://wiki.formulae.org/?script=examples/Continued_fraction this] page you can see the solution of this task.}}
 
'''Solution'''
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
The following function definition creates a continued fraction:
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
[[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 1,467 ⟶ 1,822:
fmt.Println("nap: ", cfNap(20).real())
fmt.Println("pi: ", cfPi(20).real())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,477 ⟶ 1,832:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">import java.util.function.Function
 
import static java.lang.Math.pow
Line 1,501 ⟶ 1,856:
System.out.println(calc(f, 200))
}
}</langsyntaxhighlight>
{{out}}
<pre>1.4142135623730951
Line 1,508 ⟶ 1,863:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (unfoldr)
import Data.Char (intToDigit)
 
Line 1,539 ⟶ 1,894:
(putStrLn .
take 200 . decString . (approxCF 950 :: [(Integer, Integer)] -> Rational))
[sqrt2, napier, myPi]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,546 ⟶ 1,901:
3.141592653297590947683406834261190738869139611505752231394089152890909495973464508817163306557131591579057202097715021166512662872910519439747609829479577279606075707015622200744006783543589980682386
</pre>
<langsyntaxhighlight lang="haskell">import Data.Ratio ((%), denominator, numerator)
import Data.Bool (bool)
 
-- ignoring the task-given pi sequence: sucky convergence
Line 1,562 ⟶ 1,918:
cf2rat_p p s = f $ map ((\i -> (cf2rat i s, cf2rat (1 + i) s)) . (2 ^)) [0 ..]
where
f ((x, y):ys) =
if| abs (x - y) < (1 / fromIntegral p) = x
| otherwise then= xf ys
else f ys
 
-- returns a decimal string of n digits after the dot; all digits should
Line 1,582 ⟶ 1,937:
 
main :: IO ()
main = mapM_ putStrLn [cf2dec 200 sqrt2, cf2dec 200 napier, cf2dec 200 pie]</syntaxhighlight>
 
</lang>
=={{header|Icon}}==
<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}}==
<langsyntaxhighlight Jlang="j"> cfrac=: +`% / NB. Evaluate a list as a continued fraction
 
sqrt2=: cfrac 1 1,200$2 1x
Line 1,599 ⟶ 2,014:
1.4142135623730950488016887242096980785696718753769480731766797379907324784621205551109457595775322165
3.1415924109
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274</langsyntaxhighlight>
 
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>.
Line 1,606 ⟶ 2,021:
{{trans|D}}
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import static java.lang.Math.pow;
import java.util.*;
import java.util.function.Function;
Line 1,630 ⟶ 2,045:
System.out.println(calc(f, 200));
}
}</langsyntaxhighlight>
<pre>1.4142135623730951
2.7182818284590455
Line 1,653 ⟶ 2,068:
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">
<lang jq>
# "first" is the first triple, e.g. [1,a,b];
# 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
Line 1,679 ⟶ 2,094:
end;
[2,null] | cf;
</syntaxhighlight>
</lang>
'''Examples''':
 
The convergence for pi is slow so we select delta = 1e-12 in that case.
<langsyntaxhighlight 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>
</lang>
{{Out}}
<langsyntaxhighlight 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)</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|01.68.5}}
High performant lazy evaluation on demand with Julias iterators.
<lang julia>function _sqrt(a::Bool, n)
<syntaxhighlight lang="julia">
if a
using .Iterators: countfrom, flatten, repeated, zip
return n > 0 ? 2.0 : 1.0
using .MathConstants: ℯ
else
using Printf
return 1.0
end
end
 
function _napier(a::Bool, n)
if a
return n > 0 ? Float64(n) : 2.0
else
return n > 1 ? n - 1.0 : 1.0
end
end
 
function _pi(a::Bool, n)
if a
return n > 0 ? 6.0 : 3.0
else
return (2.0 * n - 1.0) ^ 2.0 # exponentiation operator
end
end
 
function calccf(f::Functiona₀, expansions::Integera, b = repeated(1))
m = BigInt[a₀ 1; 1 0]
a, b = true, false
for (aᵢ, bᵢ) ∈ zip(a, b)
r = 0.0
for i in expansions:-1: m *= [aᵢ 1; bᵢ 0]
r = fisapprox(bm[1]/m[2], i) m[3]/m[4]; (f(a,atol i= 1e-12) +&& r)break
end
m[1]/m[2]
return f(a, 0) + r
end
 
out((k, v)) = @printf "%2s: %.12f ≈ %.12f\n" k v eval(k)
for (v, f) in (("√2", _sqrt), ("e", _napier), ("π", _pi))
@printf("%3s = %f\n", v, calc(f, 1000))
end</lang>
 
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.414214414213562373
ℯ: 2.718281828459 ≈ 2.718281828459
e = 2.718282
π: 3.141592653590 = 3.141593141592653590</pre>
 
=={{header|Klong}}==
<syntaxhighlight lang="k">
<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}
Line 1,746 ⟶ 2,146:
cf({:[0=x;2;x]};{:[x>1;x-1;x]};1000)
cf({:[0=x;3;6]};{((2*x)-1)^2};1000)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,757 ⟶ 2,157:
=={{header|Kotlin}}==
{{trans|D}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
typealias Func = (Int) -> IntArray
Line 1,777 ⟶ 2,177:
)
for (pair in pList) println("${pair.first} = ${calc(pair.second, 200)}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,785 ⟶ 2,185:
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}}
<langsyntaxhighlight lang="lua">function calc(fa, fb, expansions)
local a = 0.0
local b = 0.0
Line 1,853 ⟶ 2,313:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre>1.4142135623731
Line 1,860 ⟶ 2,320:
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
contfrac:=n->evalf(Value(NumberTheory:-ContinuedFraction(n)));
contfrac(2^(0.5));
contfrac(Pi);
contfrac(exp(1));
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="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</langsyntaxhighlight>
{{out}}
<pre>
Line 1,882 ⟶ 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 1,904 ⟶ 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 1,959 ⟶ 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 1,972 ⟶ 2,432:
 
=={{header|Nim}}==
<langsyntaxhighlight 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):
Line 1,996 ⟶ 2,456:
(a, b)
 
echo $calc(sqrt2, 20)
echo $calc(napier, 15)
echo $calc(pi, 10000)</langsyntaxhighlight>
{{out}}
<pre>1.414213562373095
Line 2,005 ⟶ 2,465:
 
=={{header|OCaml}}==
<langsyntaxhighlight 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
Line 2,018 ⟶ 2,478:
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);</langsyntaxhighlight>
Output (inaccurate due to too few terms):
<pre>sqrt(2) = 1.414213562373095
Line 2,026 ⟶ 2,486:
=={{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}}==
We'll useUse closures to implement the infinite lists of coeffficients.
 
<syntaxhighlight lang="perl">use strict;
<lang perl>sub continued_fraction {
use warnings;
my ($a, $b, $n) = (@_[0,1], $_[2] // 100);
no warnings 'recursion';
use experimental 'signatures';
 
sub continued_fraction ($a, $b, $n = 100) {
$a->() + ($n && $b->() / continued_fraction($a, $b, $n-1));
$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 };
printf "e ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ ||or 2 } }, do { my $n; sub { $n++ ||or 1 } };
printf "π ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ ? 6 : 3 } }, do { my $n; sub { (2*$n++ + 1)**2 } }, 1_0001000;
printf "π/2 ≈ %.9f\n", continued_fraction do { my $n; sub { 1/($n++ ||or 1) } }, sub { 1 }, 1_0001000;</langsyntaxhighlight>
{{out}}
<pre>√2 ≈ 1.414213562
Line 2,052 ⟶ 2,636:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
{{trans|ALGOL_68}}
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<lang Phix>function continued_fraction(integer steps, fa, fb)
<span style="color: #008080;">constant</span> <span style="color: #000000;">precision</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">10000</span>
atom res = 0
for n=steps to 1 by -1 do
<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>
res := fb(n) / (fa(n) + res)
<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>
end for
<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>
return fa(0) + res
<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>
end function
<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>
function sqr2_a(integer n) return iff(n=0?1:2) end function
<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>
function sqr2_b(integer n) return 1 end function
<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>
function nap_a(integer n) return iff(n=0?2:n) end function
function nap_b(integer n) return iff(n=1?1:n-1) end function
<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>
function pi_a(integer n) return iff(n=0?3:6) end function
<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>
function pi_b(integer n) return iff(n=1?1:power(2*n-1,2)) end function
<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>
constant precision = 10000
<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>
printf(1,"Precision: %d\n", {precision})
<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>
printf(1,"Sqr(2): %.10g\n", {continued_fraction(precision, sqr2_a, sqr2_b)})
<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>
printf(1,"Napier: %.10g\n", {continued_fraction(precision, nap_a, nap_b)})
<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>
printf(1,"Pi: %.10g\n", {continued_fraction(precision, pi_a, pi_b)})</lang>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 2,083 ⟶ 2,668:
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) ?=>
call(Compute_ab, 0, A, _),
V = A + Temp.
continued_fraction(N, Compute_ab, Tmp, V) =>
call(Compute_ab, N, A, B),
Tmp1 = B / (A + Tmp),
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
napier_ab(0, 2, _).
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>
 
{{out}}
<pre>
sqrt(2) = 1.414213562373095 (diff: 0.000000000000000)
e = 2.718281828459046 (diff: 0.000000000000000)
pi = 3.141592622804847 (diff: -0.000000030784946)
pi = 3.141592653589762 (diff: -0.000000000000031)
</pre>
 
===Iterative===
{{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].
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>
 
Which has exactly the same output as the recursive version.
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(scl 49)
(de fsqrt2 (N A)
(default A 1)
Line 2,118 ⟶ 2,780:
(prinl (format (fsqrt2 200) *Scl))
(prinl (format (napier 200) *Scl))
(prinl (format (pi 200) *Scl))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,127 ⟶ 2,789:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLIlang="pli">/* Version for SQRT(2) */
test: proc options (main);
declare n fixed;
Line 2,140 ⟶ 2,802:
put (1 + 1/denom(2));
 
end test;</langsyntaxhighlight>
{{out}}
<pre> 1.41421356237309505E+0000 </pre>
Version for NAPIER:
<langsyntaxhighlight PLIlang="pli">test: proc options (main);
declare n fixed;
 
Line 2,156 ⟶ 2,818:
put (2 + 1/denom(0));
 
end test;</langsyntaxhighlight>
<pre> 2.71828182845904524E+0000 </pre>
Version for SQRT2, NAPIER, PI
<langsyntaxhighlight PLIlang="pli">/* Derived from continued fraction in Wiki Ada program */
 
continued_fractions: /* 6 Sept. 2012 */
Line 2,202 ⟶ 2,864:
put skip edit ('PI=', calc(pi, 99999)) (a(10), f(20,17));
 
end continued_fractions;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,211 ⟶ 2,873:
 
=={{header|Prolog}}==
<langsyntaxhighlight Prologlang="prolog">continued_fraction :-
% square root 2
continued_fraction(200, sqrt_2_ab, V1),
Line 2,253 ⟶ 2,915:
pi_ab(0, 3, _).
pi_ab(N, 6, V) :-
V is (2 * N - 1)*(2 * N - 1).</langsyntaxhighlight>
{{out}}
<pre> ?- continued_fraction.
Line 2,264 ⟶ 2,926:
=={{header|Python}}==
{{works with|Python|2.6+ and 3.x}}
<langsyntaxhighlight lang="python">from fractions import Fraction
import itertools
try: zip = itertools.izip
Line 2,330 ⟶ 2,992:
cf = CF(Pi_a(), Pi_b(), 950)
print(pRes(cf, 10))
#3.1415926532</langsyntaxhighlight>
===Fast iterative version===
{{trans|D}}
<langsyntaxhighlight lang="python">from decimal import Decimal, getcontext
 
def calc(fun, n):
Line 2,356 ⟶ 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:
<langsyntaxhighlight lang="racket">
#lang racket
(define (calc cf n)
Line 2,382 ⟶ 3,083:
(calc cf-napier 200)
(calc cf-pi 200)
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="racket">
1.4142135623730951
2.7182818284590455
3.1415926839198063
</syntaxhighlight>
</lang>
 
===Version - Using Doubles===
This versions uses big floats (arbitrary precision floating point):
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 2,412 ⟶ 3,113:
(calc cf-napier 200)
(calc cf-pi 200)
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="racket">
(bf #e1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358960036439214262599769155193770031712304888324413327207659690547583107739957489062466508437105234564161085482146113860092820802430986649987683947729823677905101453725898480737256099166805538057375451207262441039818826744940289448489312217214883459060818483750848688583833366310472320771259749181255428309841375829513581694269249380272698662595131575038315461736928338289219865139248048189188905788104310928762952913687232022557677738108337499350045588767581063729)
(bf #e2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170276183860626133138458300075204493382656029760673711320070932870912744374704723624212700454495421842219077173525899689811474120614457405772696521446961165559468253835854362096088934714907384964847142748311021268578658461064714894910680584249490719358138073078291397044213736982988247857479512745588762993966446075)
(bf #e3.14159268391980626493420192940831754203350026401337226640663040854412059241988978103217808449508253393479795573626200366332733859609651462659489470805432281782785922056335606047700127154963266242144951481397480765182268219697420028007903565511884267297358842935537138583640066772149177226656227031792115896439889412205871076985598822285367358003457939603015797225018209619662200081521930463480571130673429337524564941105654923909951299948539893933654293161126559643573974163405197696633200469475250152247413175932572922175467223988860975105100904322239324381097207835036465269418118204894206705789759765527734394105147)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2015-10-31}}
<syntaxhighlight lang="raku" perl6line>sub continued-fraction(:@a, :@b, Int :$n = 100)
{
my $x = @a[$n - 1];
Line 2,432 ⟶ 3,133:
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)));</langsyntaxhighlight>
{{out}}
<pre>√2 ≈ 1.414213562
Line 2,449 ⟶ 3,150:
 
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" perl6line>sub continued-fraction(@a, @b) {
map { .(Inf) }, [\o] map { @a[$_] + @b[$_] / * }, ^Inf
}
Line 2,455 ⟶ 3,156:
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];</langsyntaxhighlight>
{{out}}
<pre>√2 ≈ 1.414213552
Line 2,476 ⟶ 3,177:
 
More code is used for nicely formatting the output than the continued fraction calculation.
<langsyntaxhighlight lang="rexx">/*REXX program calculates and displays values of various continued fractions. */
parse arg terms digs .
if terms=='' | terms=="," then terms=500
Line 2,518 ⟶ 3,219:
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. */</langsyntaxhighlight>
'''output'''
<pre>
Line 2,566 ⟶ 3,267:
 
===version 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 2,609 ⟶ 3,310:
end
call Get_Coeffs form, 0
return (A + Temp)</langsyntaxhighlight>
 
===version 3 better approximation===
<langsyntaxhighlight lang="rexx">/* REXX *************************************************************
* The task description specifies a continued fraction for pi
* that gives a reasonable approximation.
Line 2,683 ⟶ 3,384:
end
call Get_Coeffs 0
return (A + Temp)</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Continued fraction
 
Line 2,705 ⟶ 3,406:
eval("temp3=" + expr + "1" + str)
return a0 + b1 / temp3
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,711 ⟶ 3,412:
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 2,760 ⟶ 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 2,768 ⟶ 3,512:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
use std::iter;
 
Line 2,814 ⟶ 3,558:
println!("{}", continued_fraction!(pia, pib));
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,826 ⟶ 3,570:
{{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 2,856 ⟶ 3,600:
println()
}
}</langsyntaxhighlight>
{{out}}
<pre>sqrt2:
Line 2,873 ⟶ 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 2,907 ⟶ 3,651:
println()
}
}</langsyntaxhighlight>
{{out}}
<pre>sqrt2:
Line 2,927 ⟶ 3,671:
The following code relies on a library implementing SRFI 41 (lazy streams). Most Scheme interpreters include an implementation.
 
<langsyntaxhighlight lang="scheme">#!r6rs
(import (rnrs base (6))
(srfi :41 streams))
Line 2,976 ⟶ 3,720:
(stream-cons 3
(stream-cycle (build-stream (lambda (n) (expt (- (* 2 (+ n 1)) 1) 2)))
(stream-constant 6))))</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="scheme">> (cf->real sqrt2)
1.4142135623730951
> (cf->real napier)
2.7182818284590455
> (cf->real pi)
3.141592653589794</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight 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
Line 3,003 ⟶ 3,747:
for k in (params.keys.sort) {
printf("%2s ≈ %s\n", k, continued_fraction(params{k}...))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,017 ⟶ 3,761:
{{trans|Rust}}
 
<langsyntaxhighlight lang="swift">extension BinaryInteger {
@inlinable
public func power(_ n: Self) -> Self {
Line 3,123 ⟶ 3,867:
 
print("π ≈ \(continuedFraction(piA, piB))")
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,130 ⟶ 3,874:
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 3,135 ⟶ 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 3,175 ⟶ 3,952:
puts [cf r2]
puts [cf e]
puts [cf pi 250]; # Converges more slowly</langsyntaxhighlight>
{{out}}
<pre>1.4142135623730951
Line 3,182 ⟶ 3,959:
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight 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
Line 3,221 ⟶ 3,998:
Debug.Print "Napier:", continued_fraction(precision, "nap_a", "nap_b")
Debug.Print "Pi:", continued_fraction(precision, "pi_a", "pi_b")
End Sub</langsyntaxhighlight>{{out}}
<pre>Precision: 10000
Sqr(2): 1,4142135623731
Line 3,229 ⟶ 4,006:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
Function Calc(f As Func(Of Integer, Integer()), n As Integer) As Double
Dim temp = 0.0
Line 3,251 ⟶ 4,028:
End Sub
 
End Module</langsyntaxhighlight>
{{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 3,283 ⟶ 4,085:
RlOut(0, 3.0+F); CrLf(0);
RlOut(0, ACos(-1.0)); CrLf(0);
]</langsyntaxhighlight>
{{out}}
<pre>
Line 3,298 ⟶ 4,100:
 
=={{header|zkl}}==
<langsyntaxhighlight 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)
}</langsyntaxhighlight>
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.
<langsyntaxhighlight 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);</langsyntaxhighlight>
(1.0).create(n) --> n, (1.0).noop(n) --> 1.0
{{out}}
Line 3,319 ⟶ 4,121:
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<langsyntaxhighlight 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
Line 3,329 ⟶ 4,131:
1035 FOR i=1 TO n: LET p$=p$+")": NEXT i
1040 PRINT a0+b1/VAL (e$+"1"+p$)
1050 RETURN</langsyntaxhighlight>
2,120

edits