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

Georg Brandl g.brandl at gmx.net
Sun Feb 5 19:02:34 CET 2006


Alex Martelli wrote:
> 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...?

atol sounds suspicious to me, but otherwise fine.

Georg



More information about the Python-Dev mailing list