The continued fraction of a real number $x\in\mathbb R$ can be computed by the following algorithm.1
import math
def contFrac(x, k): cf = [] q = math.floor(x) cf.append(q) x = x - q i = 0 while x != 0 and i < k: q = math.floor(1 / x) cf.append(q) x = 1 / x - q i = i + 1 return cf
print(contFrac(math.sqrt(2)))
Proofs: 1
Definitions: 1
Because floating point arithmetic IEEE-754 “double precision”, python doubles contain 53 bits of precision. Therefore, the algorithm not always computes the write values of the continued fraction. The algorithm also limits the computation to 20 values of the continued fraction, since some continued fractions are not finite. ↩