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

Neil Girdhar mistersheik at gmail.com
Thu Jan 15 23:10:55 CET 2015

```The problem with this is that if your "actual" is say, 5, then a large
enough "estimate" will always be close.

On Thu, Jan 15, 2015 at 5:06 PM, Ron Adam <ron3200 at gmail.com> wrote:

>
>
> On 01/15/2015 03:47 PM, Ron Adam wrote:
>
>>
>>
>> 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
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
> --
>
> --- You received this message because you are subscribed to a topic in the
> Google Groups "python-ideas" group.
> To unsubscribe from this topic, visit https://groups.google.com/d/
> topic/python-ideas/zpfXmlTOp2I/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> python-ideas+unsubscribe at googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150115/051532af/attachment.html>
```