[Python-Dev] math.areclose ...?

Raymond Hettinger python at rcn.com
Sun Feb 5 19:48:51 CET 2006


>>So I was wondering if module math (and
>> perhaps by symmetry module cmath, too) shouldn't grow a function
>> 'areclose' (calling it just 'close' seems likely to engender
>> confusion, since 'close' is more often used as a verb than as an
>> adjective; maybe some other name would work better, e.g.
>> 'almost_equal') taking two float arguments and optional tolerances
>> and using roughly the same specs as Numeric, e.g.:
>>
>> def areclose(x,y,rtol=1.e-5,atol=1.e-8):
>>      return abs(x-y)<atol+rtol*abs(y)

IMO, the cure is worse than the disease.  It is easier to learn about
the hazards of floating point equality testing than to think through the
implications of tolerance testing (such as loss of transitivity) and 
learning
how to set the right tolerance values for a given application (ones that
give the right results across the entire domain of expected inputs).

The areclose() function can be a dangerous crutch that temporarily
glosses over the issue.  Without some numerical sophistication, it would not
be hard create programs that look correct and pass a few test but, in fact,
contain nasty bugs (non-termination, incorrect acceptance/rejection, etc).

<rant>
This proposal is one of several that have recently surfaced that aim to help
newbies skip learning basic lessons.  I think the efforts are noble but 
misguided.

* If someone doesn't get why set(1,2,3) raises an exception, it is a good
   opportunity to teach a broadly applicable skill:

       def Set(*args): return set(args)

* If someone doesn't get why sum([0.1]*10)!=1.0, then we have a good
   opportunity to teach the basics of floating point.  Otherwise, we're 
going
   to get people writing accounting apps using floats instead of ints or 
Decimals.

* If someone doesn't get how to empty a list using a[:]=[], it is a good 
time
   to go through the basics of slicing which are a foundation for 
understanding
   many parts of the language.

A language suitable for beginners should be easy to learn, but it should not
leave them permanently crippled.  All of the above are sets of training 
wheels
that don't come off.  To misquote Einstein:  The language should be as 
simple
as possible, but no simpler.
</rant>


Raymond 


More information about the Python-Dev mailing list