#!/usr/bin/env python import math def get_cont_fractions (p, maxlen=10): c_fract = [] while len (c_fract) < maxlen: c = int (math.floor (p)) c_fract.append (c) d = (p - c) if math.fabs (d) <= 0.00000001: break; p = 1.0 / d return c_fract def get_frac_from_cont_fractions (c_fract): if not c_fract: raise "Empty List as Continuos Fractions" c_f = c_fract[:] c_f.reverse () a, b = 0, 1 for i in c_f: a, b = b, i * b + a return b, a p = 1.0 for i in range (10): p *= 1.0 / (1 + math.sqrt (5.0)) * 2 print "\n%.10f:" % p for n in range (4): cf = get_cont_fractions (p, n+1) a, b = get_frac_from_cont_fractions (cf) print "%d/%d = %.10f" % (a, b, float (a) / b)