連分数展開
continued fraction
$ \pi=3+\cfrac{1}{7+\cfrac{1}{15+\cfrac{1}{1+\cfrac{1}{\ddots}}}}
小数を連分数展開する
計算誤差をいい感じに吸収しないといけないあんも.icon 元の有効数字と処理回数からいい感じに指定できる?
code:jl
function continued_frac(number::Float64, max_terms::Int; tolerance = 1e-3)
frac_terms = Int[]
for _ in 1:max_terms
integer_part = floor(Int, number)
push!(frac_terms, integer_part)
fractional_part = number - integer_part
if abs(fractional_part) < tolerance # fractional_part ≈ 0 ではうまく止まらない
break
end
number = 1 / fractional_part
end
return frac_terms
end
continued_frac(Float64(π),4)
continued_frac(0.259259, 5)
有理数型を受けるようにする
code:jl
function continued_frac(rational::Rational{Int}, max_terms::Int)
frac_terms = Int[]
nume = numerator(rational)
deno = denominator(rational)
for _ in 1:max_terms
quotient = nume ÷ deno
push!(frac_terms, quotient)
remainder = nume % deno
if remainder == 0
break
end
nume, deno = deno, remainder
end
return frac_terms
end
continued_frac(355//113, 4)
continued_frac(259//999, 5)
逆の操作で近似が得られる
円周率の近似値を得られる
有理数であれば既約分数にできる
code:jl
function rev_continued_frac(frac_terms::Vector{Int})
deno = 1
for a in reverse(frac_terms1:end-1) nume, deno = a * nume + deno, nume
end
return nume // deno
end
rev_continued_frac(continued_frac(Float64(π), 4))
rev_continued_frac(continued_frac(0.259259, 5))
rev_continued_frac(continued_frac(259//999, 5))
漸化式を利用する?