def rationalizations(x): """Generate good rational approximations of x in order of increasing denominator.""" assert 0 <= x ix = int(x) yield ix, 1 if x != ix: for numer, denom in rationalizations(1.0/(x-ix)): yield denom + ix * numer, numer import itertools, math def show(x, n): return list(itertools.islice(rationalizations(x), n)) print show(math.pi, 11) # [(3, 1), (22, 7), (333, 106), (355, 113), (103993, 33102), # (104348, 33215), (208341, 66317), (312689, 99532), # (833719, 265381), (1146408, 364913), (4272943, 1360120)]