This snippet generates the best rational approximations of a floating point number, using the method of continued fractions (tested with python 2.6 and 3.1).
Best rational approximations of a float
#!/usr/bin/env python
"""A generator of the best rational approximations of a float
using continued fractions.
(see http://en.wikipedia.org/wiki/Continued_fraction)
possible improvements left to the interested reader:
- extend the generator to support decimal.Decimal numbers.
- extend the generator to support gmpy.mpf numbers.
"""
def best_rationals(afloat):
"""generate triples (num, den, error) where num/den
is a best rational approximation of the float afloat and
error is the difference (afloat - num/den)"""
afloat, lastnum, num = ((-afloat, -1, int(-afloat))
if afloat < 0 else (afloat, 1, int(afloat)))
lastden, den = 0, 1
rest, quot = afloat, int(afloat)
while True:
yield num, den, afloat - float(num)/den
rest = 1.0/(rest - quot)
quot = int(rest)
lastnum, num, lastden, den = (num, quot * num + lastnum,
den, quot * den + lastden)
def testit():
"""Example use of best_rationals()"""
from math import pi
value = (pi ** 2) / 6
gen = best_rationals(value)
for i in range(20):
num, den, err = next(gen)
print ("{0} {1} {2:.2e}" .format(num, den, abs(err)))
if __name__ == "__main__":
testit()
Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague
TrustyTony 888 ex-Moderator Team Colleague Featured Poster
Gribouillis 1,391 Programming Explorer Team Colleague
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.