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

Alex Martelli aleaxit at gmail.com
Sun Feb 5 18:31:48 CET 2006


When teaching some programming to total newbies, a common frustration  
is how to explain why a==b is False when a and b are floats computed  
by different routes which ``should'' give the same results (if  
arithmetic had infinite precision).  Decimals can help, but another  
approach I've found useful is embodied in Numeric.allclose(a,b) --  
which returns True if all items of the arrays are ``close'' (equal to  
within certain absolute and relative tolerances):

 >>> (1.0/3.0)==(0.1/0.3)
False
 >>> Numeric.allclose(1.0/3.0, 0.1/0.3)
1

But pulling in the whole of Numeric just to have that one handy  
function is often overkill.  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)

What do y'all think...?


Alex



More information about the Python-Dev mailing list