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

Nathaniel Smith njs at pobox.com
Tue Jan 13 04:04:19 CET 2015

On 13 Jan 2015 02:52, "Alexander Belopolsky" <alexander.belopolsky at gmail.com>
> On Mon, Jan 12, 2015 at 9:32 PM, Nathaniel Smith <njs at pobox.com> wrote:
>> I don't want to step on your positive let's-fix-it attitude, I think
that's great, but... I do think you are really underestimating the
complexity of the problem.
> Didn't IEEE 754 solve this problem for us?  In IEEE 754 the bijection
between floats and integers defined by reading float bits as a 64-bit
unsigned integer preserves the total ordering and therefore the
"closeness".  For finite floats that are not too far apart the difference
between the corresponding ints is the same as the difference in ulps.
> I think something like abs(x.view(int) - y.view(int)) < ulps would be a
reasonable implementation for is_close(x, y).

This also has potentially non-intuitive behaviour near zero, and at the
least you need to do some thinking about how to handle nans and infs. This
seems to be a good article that covers a lot of these kinds of subtleties:


(Ulps also require a lot more user sophistication to understand at all, as
compared to absolute or relative tolerances.)

It does seem like adding some way to compute ulp differences to the math
module might be useful -- regardless of whether it's a panacea, it is a
useful option to have, and AFAIK there is no reasonable way to do the
computation in pure python currently.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150113/becdd464/attachment.html>

More information about the Python-ideas mailing list