In [1]:
function fractionize(x, n)
base = Float64(x)
fracs = Array(Int, n+1)
for i = 1:n+1
fracs[i] = Int(round(base, RoundDown))
if abs(base-fracs[i]) < 1e-6
return fracs[1:i]
end
base = 1/(base-fracs[i])
end
return fracs
end
Out[1]:
In [2]:
function defractionize(arr)
if length(arr) == 1
return arr[1]
else
return arr[1]+1//defractionize(arr[2:length(arr)])
end
end
Out[2]:
In [3]:
function rational_sequence(arr)
output = Array(Rational, length(arr))
for i = 1:length(arr)
output[i] = defractionize(arr[1:i])
end
return output
end
Out[3]:
In [4]:
x = rand()*10
n = 5
a = fractionize(x, n)
println(@sprintf("Die Kettenbruchkoeffizienten von %.10f sind: ", x), a)
In [12]:
x = rand()*10
n = 6
a = fractionize(x, n)
x_new = defractionize(a)
relative_error = abs(x-x_new)/x
println(@sprintf("Die Kettenbruchkoeffizienten von %.10f sind: ", x), a)
println(@sprintf("Die relative Abweichung betraegt %.10f%%", relative_error*100))
In [13]:
x = pi
n = 5
a = fractionize(x, n)
sequence = rational_sequence(a)
println("Die Kettenbruchkoeffizienten von pi sind: ", a)
println(@sprintf("Die ersten %i rationalen Näherungen sind: ", n+1), sequence)
In [ ]: