[Python-Dev] Rational approximation methods (original) (raw)

Jeffrey Yasskin jyasskin at gmail.com
Sat Jan 19 21:06:56 CET 2008


In the Rational class that I've recently checked into Python 2.6 (http://bugs.python.org/issue1682), it might be nice to provide a method that, given a particular rational number, returns a nearby number that's nicer in some way. I know of two reasonable behaviors for this operation. Since I don't know which is likely to be more useful, or even if either is useful enough to include in the first version of the module, I'm coming to you guys for advice. Both were implemented a while ago in http://svn.python.org/view/sandbox/trunk/rational/Rational.py?rev=40988&view=markup and are based on the continued fraction representation of the number (http://en.wikipedia.org/wiki/Continued_fraction#Best_rational_approximations).

The first returns the closest rational whose denominator is less than a given integer. For discussion, we might call it .limit_denominator(), although I'm also looking for good names. This seems useful for computations in which you want to sacrifice some accuracy for speed. On the other hand, Decimal may fill the niche for fast-ish computation that surprises people less than float.

The second returns the simplest rational within some distance. For instance, it'll prefer 22/7 over 333/106 if both are close enough. We might call it .simplest_within() for now. This seems useful for converting from float and displaying results to users, where we prefer readability over accuracy or have reason to believe that a simpler fraction might be more correct.

What does the list think?

Jeffrey



More information about the Python-Dev mailing list