Continued fraction: Difference between revisions

m
Line 1,913:
=={{header|Julia}}==
{{works with|Julia|1.8.5}}
High performant lazy evaluation on demand with Julias iterators.
<syntaxhighlight lang="julia">
using .Iterators: countfrom, flatten, repeated, zip
# julias iterators allow lazy evaluation on demand
using .MathConstants: ℯ
 
using .Iterators, .MathConstants, Printf
 
function cf(a₀, a, b = repeated(1))
m = BigInt[a₀ 1; 1 0]
coeffs = for (aᵢ, bᵢ) ∈ zip(a, b)
m *= [aᵢ 1; bᵢ 0]
while ! isapprox(m[1]/m[2], m[3]/m[4]; atol = 1e-9) && break
(aᵢ, bᵢ), coeffs = peel(coeffs)
end
m *= [aᵢ 1; bᵢ 0]
end
m[1]/m[2]
end
 
out((k, v)) = @printf "%2s: %.9f ≈ %.9f\n" k v eval(k)
for (k, v) in [
 
:(√2) => cf(1, repeated(2)),
foreach(out, (
:(ℯ) => cf(2, countfrom(), flatten((1, countfrom()))),
(:(π√2) =>, cf(31, repeated(6), (k^2 for k ∈ countfrom(1, 2)))],
:(:) =>, cf(2, countfrom(), flatten((1, countfrom())))),
@printf "%2s: %.9f ≈ %.9f\n" k v eval(k)
(:π, cf(3, repeated(6), (k^2 for k ∈ countfrom(1, 2))))))
end
</syntaxhighlight>
 
{{out}}
<pre>√2: 1.414213562 ≈ 1.414213562
39

edits