[Python-Dev] Re: PEP239 (Rational Numbers) Reference Implementation and new issues
Raymond Hettinger
python@rcn.com
Wed, 2 Oct 2002 22:50:56 -0400
[François Pinard]
> While I agree with the theoretical arguments, I have the practical fear that
> rationals could grow very big, rather quickly, in the course of a long
> computation involving them in various ways. By big, I mean the numerator
> and denominator of the fraction taken in isolation, not the number itself.
> Consider inversions of an integer matrices, approximations with truncated
> series, or worse things like, maybe, discrete Fourier transforms.
>
> Bigger rationals are, slower they become, and more memory they take. The
> danger is that programmers may get surprised or hurt by Python performance
> degradation, raising frequent and recurrent questions here and elsewhere.
There should be a builtin variable (overriddable within some inner scope)
for a maximum denominator magnitude. It should default to some value
where performance tanks. If set to None, then no limit would apply.
The HP32SII calculator implements a useful rational model using
flags and a maximum denominator register. If the first flag is clear,
fractions are have denominators upto the maximum value. If only
the first flag is set, fractions always use the maximum denominator
as the denominator and are then reduced (i.e. if the max is 8, then
.5 is represented as 1/2 and .1 is represented as 1/8).
[Christopher A. Craig]
> > 3) Should rationals try to hash the same as floats? My leaning on
> > this is that it will be decided by (2). If they compare equal when
> > 'close enough' then they should hash the same, if not then they should
> > only hash the same when both are integral. I would rather not see .5
> > hash with rational(1, 2) but not .2 with rational(1, 5).
[Eric Raymond]
> APL faced this problem twenty-five years ago. I like its solution;
> a `fuzz' variable defining the close-enough-for-equality range.
Instead of a global fuzz variable, I would prefer a fuzzy compare
function with a specifiable fuzz factor and a reasonable default
setting. This approach is more explicit in leaving == as an exact
compare, specifying nearlyequal(a,b) when that is what is meant,
and providing a locally specifiable factor on each compare, for
example, nearlyequal(a,b, absolute=1e-7).
Also, a fuzzy compare function could be set to use absolute or
relative differences when needed. For example:
if nearlyequal(a,b, relative=.01): # are a and b within 1%
Raymond Hettinger