[Python-ideas] Way to check for floating point "closeness"?

Ron Adam ron3200 at gmail.com
Fri Jan 16 00:45:43 CET 2015



On 01/15/2015 04:10 PM, Neil Girdhar wrote:
> The problem with this is that if your "actual" is say, 5, then a large
> enough "estimate" will always be close.

def is_close(x, y, delta=.001):
     """ Check is x and y are close to each other. """
     if x == y:
         return True           # Can't get smaller than this.
     if abs(x) < abs(y):       # Make x the larger one.
         x, y = y, x
     if x * y < 0:             # Signs differ.
         x = x - 2.0 * y         # Move x and y same distance.
         y = -y
     return (x - y)/float(x) <= delta


Do you mean the y value?

Some tests.

is_close(0, 0, delta=0.001) --> True
is_close(0, 1, delta=0.001) --> False
is_close(1, 0, delta=0.001) --> False
is_close(1000, 999, delta=0.001) --> True
is_close(999, 1000, delta=0.001) --> True
is_close(100, 95, delta=0.001) --> False
is_close(95, 100, delta=0.001) --> False
is_close(inf, 1, delta=0.001) --> False
is_close(5, 3, delta=0.001) --> False
is_close(5, 4.999, delta=0.001) --> True

is_close(0, 0, delta=0.2) --> True
is_close(0, 1, delta=0.2) --> False
is_close(1, 0, delta=0.2) --> False
is_close(1000, 999, delta=0.2) --> True
is_close(999, 1000, delta=0.2) --> True
is_close(100, 95, delta=0.2) --> True
is_close(95, 100, delta=0.2) --> True
is_close(inf, 1, delta=0.2) --> False
is_close(5, 3, delta=0.2) --> False
is_close(5, 4.999, delta=0.2) --> True


Or do you mean this?

is_close(0, 0, delta=5) --> True
is_close(0, 1, delta=5) --> True
is_close(1, 0, delta=5) --> True
is_close(1000, 999, delta=5) --> True
is_close(999, 1000, delta=5) --> True
is_close(100, 95, delta=5) --> TrueBut it's probably the best you can do 
without adding a reference length.
is_close(95, 100, delta=5) --> True
is_close(inf, 1, delta=5) --> False
is_close(5, 3, delta=5) --> True
is_close(5, 4.999, delta=5) --> True

A 1 is 100 percent the distance of the larger to 0.  So every thing except 
infinity is smaller.  A 5 is 500 percent, which is harmless as it's the 
same as 100 percent.  The smaller of the two will be located from the 
larger amount and zero.

It doesn't check for a negative delta, that should probably be an error.


Cheers,
    Ron










More information about the Python-ideas mailing list