Continued fraction: Difference between revisions
Content added Content deleted
Line 1,912: | Line 1,912: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{works with|Julia| |
{{works with|Julia|1.0}} |
||
<syntaxhighlight lang="julia"> |
<syntaxhighlight lang="julia"># julias lazy iterators allow evaluation on demand |
||
if a |
|||
return n > 0 ? 2.0 : 1.0 |
|||
else |
|||
return 1.0 |
|||
⚫ | |||
end |
|||
using .Iterators, .MathConstants, Printf |
|||
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 |
function cf(a, b = repeated(1)) |
||
a₀, a = peel(a) |
|||
m = BigInt[a₀ 1; 1 0] |
|||
coeffs = zip(a, b) |
|||
for i in expansions:-1:1 |
|||
while !isapprox(m[1]/m[2], m[3]/m[4]; atol = 1e-9) |
|||
r = f(b, i) / (f(a, i) + r) |
|||
(aᵢ, bᵢ), coeffs = peel(coeffs) |
|||
end |
|||
m *= [aᵢ 1; bᵢ 0] |
|||
return f(a, 0) + r |
|||
⚫ | |||
m[1]/m[2] |
|||
end |
end |
||
for (k, v) in [ |
|||
for (v, f) in (("√2", _sqrt), ("e", _napier), ("π", _pi)) |
|||
:(√2) => cf(flatten((1, repeated(2)))), |
|||
⚫ | |||
:(ℯ) => cf(flatten((2, countfrom())), |
|||
flatten((1, countfrom()))), |
|||
:(π) => cf(flatten((3, repeated(6))), |
|||
(k^2 for k ∈ countfrom(1, 2)))] |
|||
⚫ | |||
end</syntaxhighlight> |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre>√2: 1.414213562 ≈ 1.414213562 |
||
ℯ: 2.718281828 ≈ 2.718281828 |
|||
e = 2.718282 |
|||
π: 3.141592653 ≈ 3.141592654</pre> |
|||
=={{header|Klong}}== |
=={{header|Klong}}== |