Continued fraction: Difference between revisions
Content added Content deleted
m (→{{header|Picat}}: Added subsections, added {{out}}) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 23: | Line 23: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
< |
<syntaxhighlight lang="11l">F calc(f_a, f_b, =n = 1000) |
||
V r = 0.0 |
V r = 0.0 |
||
L n > 0 |
L n > 0 |
||
Line 32: | Line 32: | ||
print(calc(n -> I n > 0 {2} E 1, n -> 1)) |
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 {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))</ |
print(calc(n -> I n > 0 {6} E 3, n -> (2 * n - 1) ^ 2))</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
{{libheader|Action! Tool Kit}} |
{{libheader|Action! Tool Kit}} |
||
< |
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit |
||
DEFINE PTR="CARD" |
DEFINE PTR="CARD" |
||
Line 142: | Line 142: | ||
Calc(piA,piB,500,res) |
Calc(piA,piB,500,res) |
||
Print(" Pi=") PrintRE(res) |
Print(" Pi=") PrintRE(res) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Continued_fraction.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Continued_fraction.png Screenshot from Atari 8-bit computer] |
||
Line 155: | Line 155: | ||
Generic function for estimating continued fractions: |
Generic function for estimating continued fractions: |
||
< |
<syntaxhighlight lang="ada">generic |
||
type Scalar is digits <>; |
type Scalar is digits <>; |
||
with function A (N : in Natural) return Natural; |
with function A (N : in Natural) return Natural; |
||
with function B (N : in Positive) return Natural; |
with function B (N : in Positive) return Natural; |
||
function Continued_Fraction (Steps : in Natural) return Scalar;</ |
function Continued_Fraction (Steps : in Natural) return Scalar;</syntaxhighlight> |
||
< |
<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 A (N : in Natural) return Scalar is (Scalar (Natural'(A (N)))); |
||
function B (N : in Positive) return Scalar is (Scalar (Natural'(B (N)))); |
function B (N : in Positive) return Scalar is (Scalar (Natural'(B (N)))); |
||
Line 172: | Line 172: | ||
end loop; |
end loop; |
||
return A (0) + Fraction; |
return A (0) + Fraction; |
||
end Continued_Fraction;</ |
end Continued_Fraction;</syntaxhighlight> |
||
Test program using the function above to estimate the square root of 2, Napiers constant and pi: |
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; |
with Continued_Fraction; |
||
Line 208: | Line 208: | ||
Put (Napiers_Constant.Estimate (200), Exp => 0); New_Line; |
Put (Napiers_Constant.Estimate (200), Exp => 0); New_Line; |
||
Put (Pi.Estimate (10000), Exp => 0); New_Line; |
Put (Pi.Estimate (10000), Exp => 0); New_Line; |
||
end Test_Continued_Fractions;</ |
end Test_Continued_Fractions;</syntaxhighlight> |
||
===Using only Ada 95 features=== |
===Using only Ada 95 features=== |
||
This example is exactly the same as the preceding one, but implemented 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 <>; |
type Scalar is digits <>; |
||
with function A (N : in Natural) return Natural; |
with function A (N : in Natural) return Natural; |
||
with function B (N : in Positive) return Natural; |
with function B (N : in Positive) return Natural; |
||
function Continued_Fraction_Ada95 (Steps : in Natural) return Scalar;</ |
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 |
function A (N : in Natural) return Scalar is |
||
begin |
begin |
||
Line 235: | Line 235: | ||
end loop; |
end loop; |
||
return A (0) + Fraction; |
return A (0) + Fraction; |
||
end Continued_Fraction_Ada95;</ |
end Continued_Fraction_Ada95;</syntaxhighlight> |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; |
||
with Continued_Fraction_Ada95; |
with Continued_Fraction_Ada95; |
||
Line 322: | Line 322: | ||
Put (Napiers_Constant.Estimate (200), Exp => 0); New_Line; |
Put (Napiers_Constant.Estimate (200), Exp => 0); New_Line; |
||
Put (Pi.Estimate (10000), Exp => 0); New_Line; |
Put (Pi.Estimate (10000), Exp => 0); New_Line; |
||
end Test_Continued_Fractions_Ada95;</ |
end Test_Continued_Fractions_Ada95;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1.41421356237310 |
<pre> 1.41421356237310 |
||
Line 330: | Line 330: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{works with|Algol 68 Genie|2.8}} |
{{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: |
PROC cf = (INT steps, PROC (INT) INT a, PROC (INT) INT b) REAL: |
||
BEGIN |
BEGIN |
||
Line 356: | Line 356: | ||
print (("Napier: ", cf(precision, anap, bnap), newline)); |
print (("Napier: ", cf(precision, anap, bnap), newline)); |
||
print (("Pi: ", cf(precision, api, bpi))) |
print (("Pi: ", cf(precision, api, bpi))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 367: | Line 367: | ||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
{{trans|Nim}} |
{{trans|Nim}} |
||
< |
<syntaxhighlight lang="rebol">calc: function [f, n][ |
||
[a, b, temp]: 0.0 |
[a, b, temp]: 0.0 |
||
Line 396: | Line 396: | ||
print calc 'sqrt2 20 |
print calc 'sqrt2 20 |
||
print calc 'napier 15 |
print calc 'napier 15 |
||
print calc 'Pi 10000</ |
print calc 'Pi 10000</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 406: | Line 406: | ||
=={{header|ATS}}== |
=={{header|ATS}}== |
||
A fairly direct translation of the [[#C|C version]] without using advanced features of the type system: |
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" |
"share/atspre_staload.hats" |
||
// |
// |
||
Line 475: | Line 475: | ||
println! ("napier = ", calc(napier, 100)); |
println! ("napier = ", calc(napier, 100)); |
||
println! (" pi = ", calc( pi , 100)); |
println! (" pi = ", calc( pi , 100)); |
||
) (* end of [main0] *)</ |
) (* end of [main0] *)</syntaxhighlight> |
||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">sqrt2_a(n) ; function definition is as simple as that |
||
{ |
{ |
||
return n?2.0:1.0 |
return n?2.0:1.0 |
||
Line 524: | Line 524: | ||
} |
} |
||
Msgbox, % "sqrt 2 = " . calc("sqrt2", 1000) . "`ne = " . calc("napier", 1000) . "`npi = " . calc("pi", 1000)</ |
Msgbox, % "sqrt 2 = " . calc("sqrt2", 1000) . "`ne = " . calc("napier", 1000) . "`npi = " . calc("pi", 1000)</syntaxhighlight> |
||
Output with Autohotkey v1 (currently 1.1.16.05): |
Output with Autohotkey v1 (currently 1.1.16.05): |
||
< |
<syntaxhighlight lang="autohotkey">sqrt 2 = 1.414214 |
||
e = 2.718282 |
e = 2.718282 |
||
pi = 3.141593</ |
pi = 3.141593</syntaxhighlight> |
||
Output with Autohotkey v2 (currently alpha 56): |
Output with Autohotkey v2 (currently alpha 56): |
||
< |
<syntaxhighlight lang="autohotkey">sqrt 2 = 1.4142135623730951 |
||
e = 2.7182818284590455 |
e = 2.7182818284590455 |
||
pi = 3.1415926533405418</ |
pi = 3.1415926533405418</syntaxhighlight> |
||
Note the far superiour accuracy of v2. |
Note the far superiour accuracy of v2. |
||
=={{header|Axiom}}== |
=={{header|Axiom}}== |
||
Axiom provides a ContinuedFraction domain: |
Axiom provides a ContinuedFraction domain: |
||
< |
<syntaxhighlight lang="axiom">get(obj) == convergents(obj).1000 -- utility to extract the 1000th value |
||
get continuedFraction(1, repeating [1], repeating [2]) :: Float |
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(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</ |
get continuedFraction(3, [i^2 for i in 1.. by 2], repeating [6]) :: Float</syntaxhighlight> |
||
Output:< |
Output:<syntaxhighlight lang="axiom"> (1) 1.4142135623 730950488 |
||
Type: Float |
Type: Float |
||
Line 548: | Line 548: | ||
(3) 3.1415926538 39792926 |
(3) 3.1415926538 39792926 |
||
Type: Float</ |
Type: Float</syntaxhighlight> |
||
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. |
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: |
We could re-implement this, with the same output: |
||
< |
<syntaxhighlight lang="axiom">cf(initial, a, b, n) == |
||
n=1 => initial |
n=1 => initial |
||
temp := 0 |
temp := 0 |
||
Line 560: | Line 560: | ||
cf(1, repeating [1], repeating [2], 1000) :: Float |
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(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</ |
cf(3, [i^2 for i in 1.. by 2], repeating [6], 1000) :: Float</syntaxhighlight> |
||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> *FLOAT64 |
||
@% = &1001010 |
@% = &1001010 |
||
Line 579: | Line 579: | ||
expr$ += STR$(EVAL(a$)) + "+" + STR$(EVAL(b$)) + "/(" |
expr$ += STR$(EVAL(a$)) + "+" + STR$(EVAL(b$)) + "/(" |
||
UNTIL LEN(expr$) > (65500 - N) |
UNTIL LEN(expr$) > (65500 - N) |
||
= a0 + b1 / EVAL (expr$ + "1" + STRING$(N, ")"))</ |
= a0 + b1 / EVAL (expr$ + "1" + STRING$(N, ")"))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 589: | Line 589: | ||
=={{header|C}}== |
=={{header|C}}== |
||
{{works with|ANSI C}} |
{{works with|ANSI C}} |
||
< |
<syntaxhighlight lang="c">/* calculate approximations for continued fractions */ |
||
#include <stdio.h> |
#include <stdio.h> |
||
Line 659: | Line 659: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1.414213562 |
<pre> 1.414213562 |
||
Line 667: | Line 667: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
Line 692: | Line 692: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.4142135623731 |
<pre>1.4142135623731 |
||
Line 699: | Line 699: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iomanip> |
||
#include <iostream> |
#include <iostream> |
||
#include <tuple> |
#include <tuple> |
||
Line 740: | Line 740: | ||
<< calc(pi, 10000) << '\n' |
<< calc(pi, 10000) << '\n' |
||
<< std::setprecision(old_prec); // reset precision |
<< std::setprecision(old_prec); // reset precision |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 751: | Line 751: | ||
Functions don't take other functions as arguments, so I wrapped them in a dummy record each. |
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; |
var r = 0.0; |
||
Line 785: | Line 785: | ||
writeln(calc(new Sqrt2(), n)); |
writeln(calc(new Sqrt2(), n)); |
||
writeln(calc(new Napier(), n)); |
writeln(calc(new Napier(), n)); |
||
writeln(calc(new Pi(), n));</ |
writeln(calc(new Pi(), n));</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure"> |
||
(defn cfrac |
(defn cfrac |
||
[a b n] |
[a b n] |
||
Line 797: | Line 797: | ||
(def e (cfrac #(if (zero? %) 2.0 %) #(if (= 1 %) 1.0 (double (dec %))) 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)) |
(def pi (cfrac #(if (zero? %) 3.0 6.0) #(let [x (- (* 2.0 %) 1.0)] (* x x)) 900000)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 809: | Line 809: | ||
{{works with|GnuCOBOL}} |
{{works with|GnuCOBOL}} |
||
< |
<syntaxhighlight lang="cobol"> identification division. |
||
program-id. show-continued-fractions. |
program-id. show-continued-fractions. |
||
Line 994: | Line 994: | ||
goback. |
goback. |
||
end program pi-beta. |
end program pi-beta. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,003: | Line 1,003: | ||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript"># Compute a continuous fraction of the form |
||
# a0 + b1 / (a1 + b2 / (a2 + b3 / ... |
# a0 + b1 / (a1 + b2 / (a2 + b3 / ... |
||
continuous_fraction = (f) -> |
continuous_fraction = (f) -> |
||
Line 1,037: | Line 1,037: | ||
x = 2*n - 1 |
x = 2*n - 1 |
||
x * x |
x * x |
||
p Math.PI, continuous_fraction(fpi)</ |
p Math.PI, continuous_fraction(fpi)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,054: | Line 1,054: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
{{trans|C++}} |
{{trans|C++}} |
||
< |
<syntaxhighlight lang="lisp">(defun estimate-continued-fraction (generator n) |
||
(let ((temp 0)) |
(let ((temp 0)) |
||
(loop for n1 from n downto 1 |
(loop for n1 from n downto 1 |
||
Line 1,077: | Line 1,077: | ||
(* (1- (* 2 n)) |
(* (1- (* 2 n)) |
||
(1- (* 2 n))))) 10000) |
(1- (* 2 n))))) 10000) |
||
'double-float))</ |
'double-float))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>sqrt(2) = 1.4142135623730947d0 |
<pre>sqrt(2) = 1.4142135623730947d0 |
||
Line 1,084: | Line 1,084: | ||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<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 calc(FP, F)(in F fun, in int n) pure nothrow if (isCallable!F) { |
||
Line 1,114: | Line 1,114: | ||
calc!real(&fNapier, 200).print; |
calc!real(&fNapier, 200).print; |
||
calc!real(&fPi, 200).print; |
calc!real(&fPi, 200).print; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.4142135623730950487 |
<pre>1.4142135623730950487 |
||
Line 1,121: | Line 1,121: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang"> |
||
-module(continued). |
-module(continued). |
||
-compile([export_all]). |
-compile([export_all]). |
||
Line 1,165: | Line 1,165: | ||
test_nappier (N) -> |
test_nappier (N) -> |
||
continued_fraction(fun nappier_a/1,fun nappier_b/1,N). |
continued_fraction(fun nappier_a/1,fun nappier_b/1,N). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="erlang"> |
||
29> continued:test_pi(1000). |
29> continued:test_pi(1000). |
||
3.141592653340542 |
3.141592653340542 |
||
Line 1,175: | Line 1,175: | ||
31> continued:test_nappier(1000). |
31> continued:test_nappier(1000). |
||
2.7182818284590455 |
2.7182818284590455 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
===The Functions=== |
===The Functions=== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
// I provide four functions:- |
// I provide four functions:- |
||
// cf2S general purpose continued fraction to sequence of float approximations |
// cf2S general purpose continued fraction to sequence of float approximations |
||
Line 1,191: | Line 1,191: | ||
let cfSqRt n=(cf2S (fun()->n-1M) (let mutable n=false in fun()->if n then 2M else (n<-true; 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) |
let π n=let mutable π=n in (fun ()->match π with h::t->π<-t; h |_->9999999999999999999999999999M) |
||
</syntaxhighlight> |
|||
</lang> |
|||
===The Tasks=== |
===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)) |
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}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,208: | Line 1,208: | ||
1.41421355164605 < √2 < 1.41421362489487 |
1.41421355164605 < √2 < 1.41421362489487 |
||
</pre> |
</pre> |
||
< |
<syntaxhighlight lang="fsharp"> |
||
cfSqRt 0.25M |> Seq.take 30 |> Seq.iter (printfn "%1.14f") |
cfSqRt 0.25M |> Seq.take 30 |> Seq.iter (printfn "%1.14f") |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,244: | Line 1,244: | ||
0.50000000000000 |
0.50000000000000 |
||
</pre> |
</pre> |
||
< |
<syntaxhighlight lang="fsharp"> |
||
let aπ()=let mutable n=0M in (fun ()->n<-n+1M;let b=n+n-1M in b*b) |
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) |
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)) |
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}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,261: | Line 1,261: | ||
3.14140671849650 < π < 3.14183961892940 |
3.14140671849650 < π < 3.14183961892940 |
||
</pre> |
</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] |
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)) |
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}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,277: | Line 1,277: | ||
3.14159265358939 < π < 3.14159265359140 |
3.14159265358939 < π < 3.14159265359140 |
||
</pre> |
</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 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) |
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)) |
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}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,297: | Line 1,297: | ||
=={{header|Factor}}== |
=={{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. |
''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 |
||
math.ranges prettyprint sequences ; |
math.ranges prettyprint sequences ; |
||
IN: rosetta.cfrac |
IN: rosetta.cfrac |
||
Line 1,359: | Line 1,359: | ||
PRIVATE> |
PRIVATE> |
||
MAIN: main</ |
MAIN: main</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> Square root of 2: 1.414213562373095048801688724209 |
<pre> Square root of 2: 1.414213562373095048801688724209 |
||
Line 1,366: | Line 1,366: | ||
=={{header|Felix}}== |
=={{header|Felix}}== |
||
< |
<syntaxhighlight lang="felix">fun pi (n:int) : (double*double) => |
||
let a = match n with | 0 => 3.0 | _ => 6.0 endmatch in |
let a = match n with | 0 => 3.0 | _ => 6.0 endmatch in |
||
let b = pow(2.0 * n.double - 1.0, 2.0) in |
let b = pow(2.0 * n.double - 1.0, 2.0) in |
||
Line 1,392: | Line 1,392: | ||
println$ cf_iter 200 sqrt_2; // => 1.41421 |
println$ cf_iter 200 sqrt_2; // => 1.41421 |
||
println$ cf_iter 200 napier; // => 2.71818 |
println$ cf_iter 200 napier; // => 2.71818 |
||
println$ cf_iter 1000 pi; // => 3.14159</ |
println$ cf_iter 1000 pi; // => 3.14159</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
{{trans|D}} |
{{trans|D}} |
||
< |
<syntaxhighlight 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 ; |
: 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 ; |
: fpi dup 2* 1- dup * s>f 0> if 6 else 3 then s>f ; |
||
Line 1,404: | Line 1,404: | ||
do i over execute frot f+ f/ -1 +loop |
do i over execute frot f+ f/ -1 +loop |
||
0 swap execute fnip f+ \ calcucate for 0 |
0 swap execute fnip f+ \ calcucate for 0 |
||
;</ |
;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,416: | Line 1,416: | ||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
< |
<syntaxhighlight lang="fortran">module continued_fractions |
||
implicit none |
implicit none |
||
Line 1,514: | Line 1,514: | ||
end function |
end function |
||
end program examples</ |
end program examples</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,523: | Line 1,523: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">#define MAX 70000 |
||
function sqrt2_a( n as uinteger ) as uinteger |
function sqrt2_a( n as uinteger ) as uinteger |
||
Line 1,560: | Line 1,560: | ||
print calc_contfrac( @sqrt2_a, @sqrt2_b, MAX ) |
print calc_contfrac( @sqrt2_a, @sqrt2_b, MAX ) |
||
print calc_contfrac( @napi_a, @napi_b, MAX ) |
print calc_contfrac( @napi_a, @napi_b, MAX ) |
||
print calc_contfrac( @pi_a, @pi_b, MAX )</ |
print calc_contfrac( @pi_a, @pi_b, MAX )</syntaxhighlight> |
||
=={{header|Fōrmulæ}}== |
=={{header|Fōrmulæ}}== |
||
Line 1,571: | Line 1,571: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,623: | Line 1,623: | ||
fmt.Println("nap: ", cfNap(20).real()) |
fmt.Println("nap: ", cfNap(20).real()) |
||
fmt.Println("pi: ", cfPi(20).real()) |
fmt.Println("pi: ", cfPi(20).real()) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,633: | Line 1,633: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="groovy">import java.util.function.Function |
||
import static java.lang.Math.pow |
import static java.lang.Math.pow |
||
Line 1,657: | Line 1,657: | ||
System.out.println(calc(f, 200)) |
System.out.println(calc(f, 200)) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.4142135623730951 |
<pre>1.4142135623730951 |
||
Line 1,664: | Line 1,664: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import Data.List (unfoldr) |
||
import Data.Char (intToDigit) |
import Data.Char (intToDigit) |
||
Line 1,695: | Line 1,695: | ||
(putStrLn . |
(putStrLn . |
||
take 200 . decString . (approxCF 950 :: [(Integer, Integer)] -> Rational)) |
take 200 . decString . (approxCF 950 :: [(Integer, Integer)] -> Rational)) |
||
[sqrt2, napier, myPi]</ |
[sqrt2, napier, myPi]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,702: | Line 1,702: | ||
3.141592653297590947683406834261190738869139611505752231394089152890909495973464508817163306557131591579057202097715021166512662872910519439747609829479577279606075707015622200744006783543589980682386 |
3.141592653297590947683406834261190738869139611505752231394089152890909495973464508817163306557131591579057202097715021166512662872910519439747609829479577279606075707015622200744006783543589980682386 |
||
</pre> |
</pre> |
||
< |
<syntaxhighlight lang="haskell">import Data.Ratio ((%), denominator, numerator) |
||
import Data.Bool (bool) |
import Data.Bool (bool) |
||
Line 1,738: | Line 1,738: | ||
main :: IO () |
main :: IO () |
||
main = mapM_ putStrLn [cf2dec 200 sqrt2, cf2dec 200 napier, cf2dec 200 pie]</ |
main = mapM_ putStrLn [cf2dec 200 sqrt2, cf2dec 200 napier, cf2dec 200 pie]</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j"> cfrac=: +`% / NB. Evaluate a list as a continued fraction |
||
sqrt2=: cfrac 1 1,200$2 1x |
sqrt2=: cfrac 1 1,200$2 1x |
||
Line 1,754: | Line 1,754: | ||
1.4142135623730950488016887242096980785696718753769480731766797379907324784621205551109457595775322165 |
1.4142135623730950488016887242096980785696718753769480731766797379907324784621205551109457595775322165 |
||
3.1415924109 |
3.1415924109 |
||
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274</ |
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274</syntaxhighlight> |
||
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>. |
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,761: | Line 1,761: | ||
{{trans|D}} |
{{trans|D}} |
||
{{works with|Java|8}} |
{{works with|Java|8}} |
||
< |
<syntaxhighlight lang="java">import static java.lang.Math.pow; |
||
import java.util.*; |
import java.util.*; |
||
import java.util.function.Function; |
import java.util.function.Function; |
||
Line 1,785: | Line 1,785: | ||
System.out.println(calc(f, 200)); |
System.out.println(calc(f, 200)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
<pre>1.4142135623730951 |
<pre>1.4142135623730951 |
||
2.7182818284590455 |
2.7182818284590455 |
||
Line 1,808: | Line 1,808: | ||
computes the continued fraction until the difference in approximations is less than or equal to delta, |
computes the continued fraction until the difference in approximations is less than or equal to delta, |
||
which may be 0, as previously noted. |
which may be 0, as previously noted. |
||
<syntaxhighlight lang="jq"> |
|||
<lang jq> |
|||
# "first" is the first triple, |
# "first" is the first triple, |
||
# e.g. [1,a,b]; count specifies the number of terms to use. |
# e.g. [1,a,b]; count specifies the number of terms to use. |
||
Line 1,834: | Line 1,834: | ||
end; |
end; |
||
[2,null] | cf; |
[2,null] | cf; |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Examples''': |
'''Examples''': |
||
The convergence for pi is slow so we select delta = 1e-12 in that case. |
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))", |
"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))))", |
"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)" |
"pi : \(1|atan * 4) : \(continued_fraction_delta( [1,3,1]; .[0]+1 | [., 6, ((2*. - 1) | (.*.))]; 1e-12)) (1e-12)" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
< |
<syntaxhighlight lang="sh">$ jq -M -n -r -f Continued_fraction.jq |
||
Value : Direct : Continued Fraction |
Value : Direct : Continued Fraction |
||
2|sqrt : 1.4142135623730951 : 1.4142135623730951 |
2|sqrt : 1.4142135623730951 : 1.4142135623730951 |
||
1|exp : 2.718281828459045 : 2.7182818284590455 |
1|exp : 2.718281828459045 : 2.7182818284590455 |
||
pi : 3.141592653589793 : 3.1415926535892935 (1e-12)</ |
pi : 3.141592653589793 : 3.1415926535892935 (1e-12)</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{works with|Julia|0.6}} |
{{works with|Julia|0.6}} |
||
< |
<syntaxhighlight lang="julia">function _sqrt(a::Bool, n) |
||
if a |
if a |
||
return n > 0 ? 2.0 : 1.0 |
return n > 0 ? 2.0 : 1.0 |
||
Line 1,887: | Line 1,887: | ||
for (v, f) in (("√2", _sqrt), ("e", _napier), ("π", _pi)) |
for (v, f) in (("√2", _sqrt), ("e", _napier), ("π", _pi)) |
||
@printf("%3s = %f\n", v, calc(f, 1000)) |
@printf("%3s = %f\n", v, calc(f, 1000)) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,895: | Line 1,895: | ||
=={{header|Klong}}== |
=={{header|Klong}}== |
||
<syntaxhighlight lang="k"> |
|||
<lang K> |
|||
cf::{[f g i];f::x;g::y;i::z; |
cf::{[f g i];f::x;g::y;i::z; |
||
f(0)+z{i::i-1;g(i+1)%f(i+1)+x}:*0} |
f(0)+z{i::i-1;g(i+1)%f(i+1)+x}:*0} |
||
Line 1,901: | Line 1,901: | ||
cf({:[0=x;2;x]};{:[x>1;x-1;x]};1000) |
cf({:[0=x;2;x]};{:[x>1;x-1;x]};1000) |
||
cf({:[0=x;3;6]};{((2*x)-1)^2};1000) |
cf({:[0=x;3;6]};{((2*x)-1)^2};1000) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,912: | Line 1,912: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
{{trans|D}} |
{{trans|D}} |
||
< |
<syntaxhighlight lang="scala">// version 1.1.2 |
||
typealias Func = (Int) -> IntArray |
typealias Func = (Int) -> IntArray |
||
Line 1,932: | Line 1,932: | ||
) |
) |
||
for (pair in pList) println("${pair.first} = ${calc(pair.second, 200)}") |
for (pair in pList) println("${pair.first} = ${calc(pair.second, 200)}") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,943: | Line 1,943: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
<syntaxhighlight lang="scheme"> |
|||
<lang Scheme> |
|||
{def gcf |
{def gcf |
||
Line 1,998: | Line 1,998: | ||
// Much quicker, 15 exact decimals after 15 iterations |
// Much quicker, 15 exact decimals after 15 iterations |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="lua">function calc(fa, fb, expansions) |
||
local a = 0.0 |
local a = 0.0 |
||
local b = 0.0 |
local b = 0.0 |
||
Line 2,068: | Line 2,068: | ||
end |
end |
||
main()</ |
main()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.4142135623731 |
<pre>1.4142135623731 |
||
Line 2,075: | Line 2,075: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
contfrac:=n->evalf(Value(NumberTheory:-ContinuedFraction(n))); |
contfrac:=n->evalf(Value(NumberTheory:-ContinuedFraction(n))); |
||
contfrac(2^(0.5)); |
contfrac(2^(0.5)); |
||
contfrac(Pi); |
contfrac(Pi); |
||
contfrac(exp(1)); |
contfrac(exp(1)); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{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]}}]; |
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]}}]; |
pi=Function[n,{3,Transpose@{Array[6&,n],Array[(2#-1)^2&,n]}}]; |
||
approx=Function[l, |
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]]; |
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</ |
r2=approx/@{sqrt2@#,napier@#,pi@#}&@10000;r2//TableForm</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,097: | Line 2,097: | ||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight 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)$ |
for i from n step -1 thru 2 do z: b[i]/(a[i] + z), a[1] + z)$ |
||
Line 2,119: | Line 2,119: | ||
fpprec: 20$ |
fpprec: 20$ |
||
x: cfeval(cf_pi(10000))$ |
x: cfeval(cf_pi(10000))$ |
||
bfloat(x - %pi); /* 2.4999999900104930006b-13 */</ |
bfloat(x - %pi); /* 2.4999999900104930006b-13 */</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* REXX *************************************************************** |
||
* Derived from REXX ... Derived from PL/I with a little "massage" |
* Derived from REXX ... Derived from PL/I with a little "massage" |
||
* SQRT2= 1.41421356237309505 <- PL/I Result |
* SQRT2= 1.41421356237309505 <- PL/I Result |
||
Line 2,174: | Line 2,174: | ||
end |
end |
||
Get_Coeffs(form,0) |
Get_Coeffs(form,0) |
||
return (a + temp)</ |
return (a + temp)</syntaxhighlight> |
||
Who could help me make a,b,sqrt2,napier,pi global (public) variables? |
Who could help me make a,b,sqrt2,napier,pi global (public) variables? |
||
This would simplify the solution:-) |
This would simplify the solution:-) |
||
Line 2,187: | Line 2,187: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">proc calc(f: proc(n: int): tuple[a, b: float], n: int): float = |
||
var a, b, temp = 0.0 |
var a, b, temp = 0.0 |
||
for i in countdown(n, 1): |
for i in countdown(n, 1): |
||
Line 2,213: | Line 2,213: | ||
echo calc(sqrt2, 20) |
echo calc(sqrt2, 20) |
||
echo calc(napier, 15) |
echo calc(napier, 15) |
||
echo calc(pi, 10000)</ |
echo calc(pi, 10000)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.414213562373095 |
<pre>1.414213562373095 |
||
Line 2,220: | Line 2,220: | ||
=={{header|OCaml}}== |
=={{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 nap = 2, fun n -> (max 1 (n-1), n) |
||
and root2 = 1, fun n -> (1, 2) in |
and root2 = 1, fun n -> (1, 2) in |
||
Line 2,233: | Line 2,233: | ||
Printf.printf "sqrt(2)\t= %.15f\n" (eval root2 1000); |
Printf.printf "sqrt(2)\t= %.15f\n" (eval root2 1000); |
||
Printf.printf "e\t= %.15f\n" (eval nap 1000); |
Printf.printf "e\t= %.15f\n" (eval nap 1000); |
||
Printf.printf "pi\t= %.15f\n" (eval pi 1000);</ |
Printf.printf "pi\t= %.15f\n" (eval pi 1000);</syntaxhighlight> |
||
Output (inaccurate due to too few terms): |
Output (inaccurate due to too few terms): |
||
<pre>sqrt(2) = 1.414213562373095 |
<pre>sqrt(2) = 1.414213562373095 |
||
Line 2,241: | Line 2,241: | ||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Partial solution for simple continued fractions. |
Partial solution for simple continued fractions. |
||
< |
<syntaxhighlight lang="parigp">back(v)=my(t=contfracpnqn(v));t[1,1]/t[2,1]*1. |
||
back(vector(100,i,2-(i==1)))</ |
back(vector(100,i,2-(i==1)))</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,250: | Line 2,250: | ||
Use closures to implement the infinite lists of coeffficients. |
Use closures to implement the infinite lists of coeffficients. |
||
< |
<syntaxhighlight lang="perl">use strict; |
||
use warnings; |
use warnings; |
||
no warnings 'recursion'; |
no warnings 'recursion'; |
||
Line 2,262: | Line 2,262: | ||
printf "e ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ or 2 } }, do { my $n; sub { $n++ or 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 } }, 1000; |
printf "π ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ ? 6 : 3 } }, do { my $n; sub { (2*$n++ + 1)**2 } }, 1000; |
||
printf "π/2 ≈ %.9f\n", continued_fraction do { my $n; sub { 1/($n++ or 1) } }, sub { 1 }, 1000;</ |
printf "π/2 ≈ %.9f\n", continued_fraction do { my $n; sub { 1/($n++ or 1) } }, sub { 1 }, 1000;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>√2 ≈ 1.414213562 |
<pre>√2 ≈ 1.414213562 |
||
Line 2,270: | Line 2,270: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<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;">constant</span> <span style="color: #000000;">precision</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">10000</span> |
||
Line 2,294: | Line 2,294: | ||
<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;">"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> |
<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}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 2,308: | Line 2,308: | ||
===Recursion=== |
===Recursion=== |
||
{{trans|Prolog}} |
{{trans|Prolog}} |
||
< |
<syntaxhighlight lang="picat">go => |
||
% square root 2 |
% square root 2 |
||
Line 2,352: | Line 2,352: | ||
pi_ab(0, 3, _). |
pi_ab(0, 3, _). |
||
pi_ab(N, 6, V) :- |
pi_ab(N, 6, V) :- |
||
V is (2 * N - 1)*(2 * N - 1).</ |
V is (2 * N - 1)*(2 * N - 1).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,365: | Line 2,365: | ||
{{trans|Python}} |
{{trans|Python}} |
||
(from Python's Fast Iterative version) |
(from Python's Fast Iterative version) |
||
< |
<syntaxhighlight lang="picat">continued_fraction_it(Fun, N) = Ret => |
||
Temp = 0.0, |
Temp = 0.0, |
||
foreach(I in N..-1..1) |
foreach(I in N..-1..1) |
||
Line 2,376: | Line 2,376: | ||
fsqrt2(N) = [cond(N > 0, 2, 1),1]. |
fsqrt2(N) = [cond(N > 0, 2, 1),1]. |
||
fnapier(N) = [cond(N > 0, N,2), cond(N>1,N-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].</ |
fpi(N) = [cond(N>0,6,3), (2*N-1) ** 2].</syntaxhighlight> |
||
Which has exactly the same output as the recursive version. |
Which has exactly the same output as the recursive version. |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(scl 49) |
||
(de fsqrt2 (N A) |
(de fsqrt2 (N A) |
||
(default A 1) |
(default A 1) |
||
Line 2,414: | Line 2,414: | ||
(prinl (format (fsqrt2 200) *Scl)) |
(prinl (format (fsqrt2 200) *Scl)) |
||
(prinl (format (napier 200) *Scl)) |
(prinl (format (napier 200) *Scl)) |
||
(prinl (format (pi 200) *Scl))</ |
(prinl (format (pi 200) *Scl))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,423: | Line 2,423: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli">/* Version for SQRT(2) */ |
||
test: proc options (main); |
test: proc options (main); |
||
declare n fixed; |
declare n fixed; |
||
Line 2,436: | Line 2,436: | ||
put (1 + 1/denom(2)); |
put (1 + 1/denom(2)); |
||
end test;</ |
end test;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1.41421356237309505E+0000 </pre> |
<pre> 1.41421356237309505E+0000 </pre> |
||
Version for NAPIER: |
Version for NAPIER: |
||
< |
<syntaxhighlight lang="pli">test: proc options (main); |
||
declare n fixed; |
declare n fixed; |
||
Line 2,452: | Line 2,452: | ||
put (2 + 1/denom(0)); |
put (2 + 1/denom(0)); |
||
end test;</ |
end test;</syntaxhighlight> |
||
<pre> 2.71828182845904524E+0000 </pre> |
<pre> 2.71828182845904524E+0000 </pre> |
||
Version for SQRT2, NAPIER, PI |
Version for SQRT2, NAPIER, PI |
||
< |
<syntaxhighlight lang="pli">/* Derived from continued fraction in Wiki Ada program */ |
||
continued_fractions: /* 6 Sept. 2012 */ |
continued_fractions: /* 6 Sept. 2012 */ |
||
Line 2,498: | Line 2,498: | ||
put skip edit ('PI=', calc(pi, 99999)) (a(10), f(20,17)); |
put skip edit ('PI=', calc(pi, 99999)) (a(10), f(20,17)); |
||
end continued_fractions;</ |
end continued_fractions;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,507: | Line 2,507: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
< |
<syntaxhighlight lang="prolog">continued_fraction :- |
||
% square root 2 |
% square root 2 |
||
continued_fraction(200, sqrt_2_ab, V1), |
continued_fraction(200, sqrt_2_ab, V1), |
||
Line 2,549: | Line 2,549: | ||
pi_ab(0, 3, _). |
pi_ab(0, 3, _). |
||
pi_ab(N, 6, V) :- |
pi_ab(N, 6, V) :- |
||
V is (2 * N - 1)*(2 * N - 1).</ |
V is (2 * N - 1)*(2 * N - 1).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> ?- continued_fraction. |
<pre> ?- continued_fraction. |
||
Line 2,560: | Line 2,560: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
{{works with|Python|2.6+ and 3.x}} |
{{works with|Python|2.6+ and 3.x}} |
||
< |
<syntaxhighlight lang="python">from fractions import Fraction |
||
import itertools |
import itertools |
||
try: zip = itertools.izip |
try: zip = itertools.izip |
||
Line 2,626: | Line 2,626: | ||
cf = CF(Pi_a(), Pi_b(), 950) |
cf = CF(Pi_a(), Pi_b(), 950) |
||
print(pRes(cf, 10)) |
print(pRes(cf, 10)) |
||
#3.1415926532</ |
#3.1415926532</syntaxhighlight> |
||
===Fast iterative version=== |
===Fast iterative version=== |
||
{{trans|D}} |
{{trans|D}} |
||
< |
<syntaxhighlight lang="python">from decimal import Decimal, getcontext |
||
def calc(fun, n): |
def calc(fun, n): |
||
Line 2,652: | Line 2,652: | ||
print calc(fsqrt2, 200) |
print calc(fsqrt2, 200) |
||
print calc(fnapier, 200) |
print calc(fnapier, 200) |
||
print calc(fpi, 200)</ |
print calc(fpi, 200)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.4142135623730950488016887242096980785696718753770 |
<pre>1.4142135623730950488016887242096980785696718753770 |
||
Line 2,660: | Line 2,660: | ||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery"> [ $ "bigrat.qky" loadfile ] now! |
||
[ 1 min |
[ 1 min |
||
Line 2,689: | Line 2,689: | ||
1000 cf sqrt2 10 point$ echo$ cr |
1000 cf sqrt2 10 point$ echo$ cr |
||
1000 cf napier 10 point$ echo$ cr |
1000 cf napier 10 point$ echo$ cr |
||
1000 cf pi 10 point$ echo$ cr</ |
1000 cf pi 10 point$ echo$ cr</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,700: | Line 2,700: | ||
===Using Doubles=== |
===Using Doubles=== |
||
This version uses standard double precision floating point numbers: |
This version uses standard double precision floating point numbers: |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(define (calc cf n) |
(define (calc cf n) |
||
Line 2,717: | Line 2,717: | ||
(calc cf-napier 200) |
(calc cf-napier 200) |
||
(calc cf-pi 200) |
(calc cf-pi 200) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
< |
<syntaxhighlight lang="racket"> |
||
1.4142135623730951 |
1.4142135623730951 |
||
2.7182818284590455 |
2.7182818284590455 |
||
3.1415926839198063 |
3.1415926839198063 |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Version - Using Doubles=== |
===Version - Using Doubles=== |
||
This versions uses big floats (arbitrary precision floating point): |
This versions uses big floats (arbitrary precision floating point): |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(require math) |
(require math) |
||
Line 2,747: | Line 2,747: | ||
(calc cf-napier 200) |
(calc cf-napier 200) |
||
(calc cf-pi 200) |
(calc cf-pi 200) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
< |
<syntaxhighlight lang="racket"> |
||
(bf #e1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358960036439214262599769155193770031712304888324413327207659690547583107739957489062466508437105234564161085482146113860092820802430986649987683947729823677905101453725898480737256099166805538057375451207262441039818826744940289448489312217214883459060818483750848688583833366310472320771259749181255428309841375829513581694269249380272698662595131575038315461736928338289219865139248048189188905788104310928762952913687232022557677738108337499350045588767581063729) |
(bf #e1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358960036439214262599769155193770031712304888324413327207659690547583107739957489062466508437105234564161085482146113860092820802430986649987683947729823677905101453725898480737256099166805538057375451207262441039818826744940289448489312217214883459060818483750848688583833366310472320771259749181255428309841375829513581694269249380272698662595131575038315461736928338289219865139248048189188905788104310928762952913687232022557677738108337499350045588767581063729) |
||
(bf #e2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170276183860626133138458300075204493382656029760673711320070932870912744374704723624212700454495421842219077173525899689811474120614457405772696521446961165559468253835854362096088934714907384964847142748311021268578658461064714894910680584249490719358138073078291397044213736982988247857479512745588762993966446075) |
(bf #e2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170276183860626133138458300075204493382656029760673711320070932870912744374704723624212700454495421842219077173525899689811474120614457405772696521446961165559468253835854362096088934714907384964847142748311021268578658461064714894910680584249490719358138073078291397044213736982988247857479512745588762993966446075) |
||
(bf #e3.14159268391980626493420192940831754203350026401337226640663040854412059241988978103217808449508253393479795573626200366332733859609651462659489470805432281782785922056335606047700127154963266242144951481397480765182268219697420028007903565511884267297358842935537138583640066772149177226656227031792115896439889412205871076985598822285367358003457939603015797225018209619662200081521930463480571130673429337524564941105654923909951299948539893933654293161126559643573974163405197696633200469475250152247413175932572922175467223988860975105100904322239324381097207835036465269418118204894206705789759765527734394105147) |
(bf #e3.14159268391980626493420192940831754203350026401337226640663040854412059241988978103217808449508253393479795573626200366332733859609651462659489470805432281782785922056335606047700127154963266242144951481397480765182268219697420028007903565511884267297358842935537138583640066772149177226656227031792115896439889412205871076985598822285367358003457939603015797225018209619662200081521930463480571130673429337524564941105654923909951299948539893933654293161126559643573974163405197696633200469475250152247413175932572922175467223988860975105100904322239324381097207835036465269418118204894206705789759765527734394105147) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
{{Works with|rakudo|2015-10-31}} |
{{Works with|rakudo|2015-10-31}} |
||
<lang |
<syntaxhighlight lang="raku" line>sub continued-fraction(:@a, :@b, Int :$n = 100) |
||
{ |
{ |
||
my $x = @a[$n - 1]; |
my $x = @a[$n - 1]; |
||
Line 2,767: | Line 2,767: | ||
printf "√2 ≈%.9f\n", continued-fraction(:a(1, |(2 xx *)), :b(Nil, |(1 xx *))); |
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 "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)));</ |
printf "π ≈%.9f\n", continued-fraction(:a(3, |(6 xx *)), :b(Nil, |((1, 3, 5 ... *) X** 2)));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>√2 ≈ 1.414213562 |
<pre>√2 ≈ 1.414213562 |
||
Line 2,784: | Line 2,784: | ||
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). |
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). |
||
<lang |
<syntaxhighlight lang="raku" line>sub continued-fraction(@a, @b) { |
||
map { .(Inf) }, [\o] map { @a[$_] + @b[$_] / * }, ^Inf |
map { .(Inf) }, [\o] map { @a[$_] + @b[$_] / * }, ^Inf |
||
} |
} |
||
Line 2,790: | Line 2,790: | ||
printf "√2 ≈ %.9f\n", continued-fraction((1, |(2 xx *)), (1 xx *))[10]; |
printf "√2 ≈ %.9f\n", continued-fraction((1, |(2 xx *)), (1 xx *))[10]; |
||
printf "e ≈ %.9f\n", continued-fraction((2, |(1 .. *)), (1, |(1 .. *)))[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];</ |
printf "π ≈ %.9f\n", continued-fraction((3, |(6 xx *)), ((1, 3, 5 ... *) X** 2))[100];</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>√2 ≈ 1.414213552 |
<pre>√2 ≈ 1.414213552 |
||
Line 2,811: | Line 2,811: | ||
More code is used for nicely formatting the output than the continued fraction calculation. |
More code is used for nicely formatting the output than the continued fraction calculation. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program calculates and displays values of various continued fractions. */ |
||
parse arg terms digs . |
parse arg terms digs . |
||
if terms=='' | terms=="," then terms=500 |
if terms=='' | terms=="," then terms=500 |
||
Line 2,853: | Line 2,853: | ||
say right(?,8) "=" $ ' α terms='aT ... |
say right(?,8) "=" $ ' α terms='aT ... |
||
if b.1\==1 then say right("",12+digits()) ' ß terms='bT ... |
if b.1\==1 then say right("",12+digits()) ' ß terms='bT ... |
||
a=; b.=1; return /*only 50 bytes of α & ß terms ↑ are displayed. */</ |
a=; b.=1; return /*only 50 bytes of α & ß terms ↑ are displayed. */</syntaxhighlight> |
||
'''output''' |
'''output''' |
||
<pre> |
<pre> |
||
Line 2,901: | Line 2,901: | ||
===version 2 derived from [[#PL/I|PL/I]]=== |
===version 2 derived from [[#PL/I|PL/I]]=== |
||
< |
<syntaxhighlight lang="rexx">/* REXX ************************************************************** |
||
* Derived from PL/I with a little "massage" |
* Derived from PL/I with a little "massage" |
||
* SQRT2= 1.41421356237309505 <- PL/I Result |
* SQRT2= 1.41421356237309505 <- PL/I Result |
||
Line 2,944: | Line 2,944: | ||
end |
end |
||
call Get_Coeffs form, 0 |
call Get_Coeffs form, 0 |
||
return (A + Temp)</ |
return (A + Temp)</syntaxhighlight> |
||
===version 3 better approximation=== |
===version 3 better approximation=== |
||
< |
<syntaxhighlight lang="rexx">/* REXX ************************************************************* |
||
* The task description specifies a continued fraction for pi |
* The task description specifies a continued fraction for pi |
||
* that gives a reasonable approximation. |
* that gives a reasonable approximation. |
||
Line 3,018: | Line 3,018: | ||
end |
end |
||
call Get_Coeffs 0 |
call Get_Coeffs 0 |
||
return (A + Temp)</ |
return (A + Temp)</syntaxhighlight> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
# Project : Continued fraction |
# Project : Continued fraction |
||
Line 3,040: | Line 3,040: | ||
eval("temp3=" + expr + "1" + str) |
eval("temp3=" + expr + "1" + str) |
||
return a0 + b1 / temp3 |
return a0 + b1 / temp3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,049: | Line 3,049: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">require 'bigdecimal' |
||
# square root of 2 |
# square root of 2 |
||
Line 3,095: | Line 3,095: | ||
puts estimate(sqrt2, 50).to_s('F') |
puts estimate(sqrt2, 50).to_s('F') |
||
puts estimate(napier, 50).to_s('F') |
puts estimate(napier, 50).to_s('F') |
||
puts estimate(pi, 10).to_s('F')</ |
puts estimate(pi, 10).to_s('F')</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>$ ruby cfrac.rb |
<pre>$ ruby cfrac.rb |
||
Line 3,103: | Line 3,103: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust"> |
||
use std::iter; |
use std::iter; |
||
Line 3,149: | Line 3,149: | ||
println!("{}", continued_fraction!(pia, pib)); |
println!("{}", continued_fraction!(pia, pib)); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,161: | Line 3,161: | ||
{{works with|Scala|2.9.1}} |
{{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. |
Note that Scala-BigDecimal provides a precision of 34 digits. Therefore we take a limitation of 32 digits to avoiding rounding problems. |
||
< |
<syntaxhighlight lang="scala">object CF extends App { |
||
import Stream._ |
import Stream._ |
||
val sqrt2 = 1 #:: from(2,0) zip from(1,0) |
val sqrt2 = 1 #:: from(2,0) zip from(1,0) |
||
Line 3,191: | Line 3,191: | ||
println() |
println() |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>sqrt2: |
<pre>sqrt2: |
||
Line 3,208: | Line 3,208: | ||
precision: 3.14159265358</pre> |
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: |
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: |
||
< |
<syntaxhighlight lang="scala">object CFI extends App { |
||
import Stream._ |
import Stream._ |
||
val sqrt2 = 1 #:: from(2,0) zip from(1,0) |
val sqrt2 = 1 #:: from(2,0) zip from(1,0) |
||
Line 3,242: | Line 3,242: | ||
println() |
println() |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>sqrt2: |
<pre>sqrt2: |
||
Line 3,262: | Line 3,262: | ||
The following code relies on a library implementing SRFI 41 (lazy streams). Most Scheme interpreters include an implementation. |
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)) |
(import (rnrs base (6)) |
||
(srfi :41 streams)) |
(srfi :41 streams)) |
||
Line 3,311: | Line 3,311: | ||
(stream-cons 3 |
(stream-cons 3 |
||
(stream-cycle (build-stream (lambda (n) (expt (- (* 2 (+ n 1)) 1) 2))) |
(stream-cycle (build-stream (lambda (n) (expt (- (* 2 (+ n 1)) 1) 2))) |
||
(stream-constant 6))))</ |
(stream-constant 6))))</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang="scheme">> (cf->real sqrt2) |
||
1.4142135623730951 |
1.4142135623730951 |
||
> (cf->real napier) |
> (cf->real napier) |
||
2.7182818284590455 |
2.7182818284590455 |
||
> (cf->real pi) |
> (cf->real pi) |
||
3.141592653589794</ |
3.141592653589794</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func continued_fraction(a, b, f, n = 1000, r = 1) { |
||
f(func (r) { |
f(func (r) { |
||
r < n ? (a(r) / (b(r) + __FUNC__(r+1))) : 0 |
r < n ? (a(r) / (b(r) + __FUNC__(r+1))) : 0 |
||
Line 3,338: | Line 3,338: | ||
for k in (params.keys.sort) { |
for k in (params.keys.sort) { |
||
printf("%2s ≈ %s\n", k, continued_fraction(params{k}...)) |
printf("%2s ≈ %s\n", k, continued_fraction(params{k}...)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,352: | Line 3,352: | ||
{{trans|Rust}} |
{{trans|Rust}} |
||
< |
<syntaxhighlight lang="swift">extension BinaryInteger { |
||
@inlinable |
@inlinable |
||
public func power(_ n: Self) -> Self { |
public func power(_ n: Self) -> Self { |
||
Line 3,458: | Line 3,458: | ||
print("π ≈ \(continuedFraction(piA, piB))") |
print("π ≈ \(continuedFraction(piA, piB))") |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,470: | Line 3,470: | ||
{{trans|Python}} |
{{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. |
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. |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.6 |
||
# Term generators; yield list of pairs |
# Term generators; yield list of pairs |
||
Line 3,510: | Line 3,510: | ||
puts [cf r2] |
puts [cf r2] |
||
puts [cf e] |
puts [cf e] |
||
puts [cf pi 250]; # Converges more slowly</ |
puts [cf pi 250]; # Converges more slowly</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.4142135623730951 |
<pre>1.4142135623730951 |
||
Line 3,517: | Line 3,517: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
{{trans|Phix}}< |
{{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 |
Private Function continued_fraction(steps As Integer, rid_a As String, rid_b As String) As Double |
||
Dim res As Double |
Dim res As Double |
||
Line 3,556: | Line 3,556: | ||
Debug.Print "Napier:", continued_fraction(precision, "nap_a", "nap_b") |
Debug.Print "Napier:", continued_fraction(precision, "nap_a", "nap_b") |
||
Debug.Print "Pi:", continued_fraction(precision, "pi_a", "pi_b") |
Debug.Print "Pi:", continued_fraction(precision, "pi_a", "pi_b") |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre>Precision: 10000 |
<pre>Precision: 10000 |
||
Sqr(2): 1,4142135623731 |
Sqr(2): 1,4142135623731 |
||
Line 3,564: | Line 3,564: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang="vbnet">Module Module1 |
||
Function Calc(f As Func(Of Integer, Integer()), n As Integer) As Double |
Function Calc(f As Func(Of Integer, Integer()), n As Integer) As Double |
||
Dim temp = 0.0 |
Dim temp = 0.0 |
||
Line 3,586: | Line 3,586: | ||
End Sub |
End Sub |
||
End Module</ |
End Module</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.4142135623731 |
<pre>1.4142135623731 |
||
Line 3,594: | Line 3,594: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{trans|D}} |
{{trans|D}} |
||
< |
<syntaxhighlight lang="ecmascript">var calc = Fn.new { |f, n| |
||
var t = 0 |
var t = 0 |
||
for (i in n..1) { |
for (i in n..1) { |
||
Line 3,608: | Line 3,608: | ||
["pi ", Fn.new { |n| [(n > 0) ? 6 : 3, (2*n - 1) * (2*n - 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))")</ |
for (p in pList) System.print("%(p[0]) = %(calc.call(p[1], 200))")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,619: | Line 3,619: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
The number of iterations (N) needed to get the 13 digits of accuracy was determined by experiment. |
The number of iterations (N) needed to get the 13 digits of accuracy was determined by experiment. |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; |
||
int N; |
int N; |
||
real A, B, F; |
real A, B, F; |
||
Line 3,643: | Line 3,643: | ||
RlOut(0, 3.0+F); CrLf(0); |
RlOut(0, 3.0+F); CrLf(0); |
||
RlOut(0, ACos(-1.0)); CrLf(0); |
RlOut(0, ACos(-1.0)); CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,658: | Line 3,658: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">fcn cf(fa,fb,a0){fcn(fa,fb,a0,n){ |
||
a0 + [n..1,-1].reduce( |
a0 + [n..1,-1].reduce( |
||
'wrap(p,n){ fb(n)/(fa(n)+p) },0.0) }.fp(fa,fb,a0) |
'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. |
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(); |
sqrt2(200) : "%.20e".fmt(_).println(); |
||
nap:=cf((0.0).create,fcn(n){ (n==1) and 1.0 or (n-1).toFloat() },2.0); |
nap:=cf((0.0).create,fcn(n){ (n==1) and 1.0 or (n-1).toFloat() },2.0); |
||
println(nap(15) - (1.0).e); |
println(nap(15) - (1.0).e); |
||
pi:=cf((6.0).noop,fcn(n){ n=2*n-1; (n*n).toFloat() },3.0); |
pi:=cf((6.0).noop,fcn(n){ n=2*n-1; (n*n).toFloat() },3.0); |
||
println(pi(1000) - (1.0).pi);</ |
println(pi(1000) - (1.0).pi);</syntaxhighlight> |
||
(1.0).create(n) --> n, (1.0).noop(n) --> 1.0 |
(1.0).create(n) --> n, (1.0).noop(n) --> 1.0 |
||
{{out}} |
{{out}} |
||
Line 3,679: | Line 3,679: | ||
=={{header|ZX Spectrum Basic}}== |
=={{header|ZX Spectrum Basic}}== |
||
{{trans|BBC_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 |
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 |
30 LET a0=3: LET b1=1: LET a$="6": LET b$="(2*N+1)^2": PRINT "PI = ";: GO SUB 1000 |
||
Line 3,689: | Line 3,689: | ||
1035 FOR i=1 TO n: LET p$=p$+")": NEXT i |
1035 FOR i=1 TO n: LET p$=p$+")": NEXT i |
||
1040 PRINT a0+b1/VAL (e$+"1"+p$) |
1040 PRINT a0+b1/VAL (e$+"1"+p$) |
||
1050 RETURN</ |
1050 RETURN</syntaxhighlight> |