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

Ron Adam ron3200 at gmail.com
Thu Jan 15 23:06:15 CET 2015



On 01/15/2015 03:47 PM, Ron Adam wrote:
> How about this?
>
>
> 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 x == 0 or y == 0:
>          return False          # Nothing is close to zero.
>      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


Remove the check of one being zero, it isn't needed.

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


If one of them is zero, then you get a ratio of one. So a delta of 1 would 
mean everything is close.

-Ron



More information about the Python-ideas mailing list