Continued fraction: Difference between revisions

m
 
(8 intermediate revisions by 6 users not shown)
Line 1,119:
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}}==
Line 1,584 ⟶ 1,694:
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Continued_fraction}}
 
'''Solution'''
 
The following function definition creates a continued fraction:
Line 1,612 ⟶ 1,724:
[[File:Fōrmulæ - Continued fraction 03.png]]
 
'''Case 1.''' <math>\sqrt 2</math>
 
In this case
Line 1,633 ⟶ 1,745:
[[File:Fōrmulæ - Continued fraction 05.png]]
 
'''Case 2.''' <math>e</math>
 
In this case
Line 1,639 ⟶ 1,751:
* a₀ is 2
* λa is n ↦ n
* λb is n ↦ 1 if n = 1, n - 1 elsewhere
 
[[File:Fōrmulæ - Continued fraction 06.png]]
Line 1,645 ⟶ 1,757:
[[File:Fōrmulæ - Continued fraction 07.png]]
 
'''Case 3.''' <math>\pi</math>
 
In this case
Line 3,319 ⟶ 3,431:
≫ ≫ ‘'''→CFRAC'''’ STO
|
'''→CFRAC''' ''( a0 aNan b1 bNbn nN -- x ) ''
Unstack an and bn
Loop from N to 2
Calculate nthNth fraction
Decrement counter
Calculate last fraction with b1 in stack, then add a0
Line 3,924 ⟶ 4,036:
=={{header|Wren}}==
{{trans|D}}
<syntaxhighlight lang="ecmascriptwren">var calc = Fn.new { |f, n|
var t = 0
for (i in n..1) {
2,120

edits