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

Steven D'Aprano steve at pearwood.info
Tue Jan 13 13:06:13 CET 2015


On Tue, Jan 13, 2015 at 09:28:39AM +0000, Mark Dickinson wrote:
> On Tue, Jan 13, 2015 at 1:34 AM, Steven D'Aprano <steve at pearwood.info>
> wrote:
> 
> > Unfortunately a naive ULP comparison has trouble with NANs, INFs, and
> > numbers close to zero, especially if they have opposite signs. The
> > smallest representable denormalised floats larger, and smaller, than
> > zero are:
> >
> > 5e-324
> > -5e-324
> >
> > These are the smallest magnitude floats apart from zero, so we might
> > hope that they are considered "close together", but they actually differ
> > by 9223372036854775808 ULP. Ouch.
> >
> 
> Only with a naive (i.e., wrong :-) implementation. 

Well, I said I was still learning :-) In my defence, I was influenced by 
Bruce Dawson who said you can't do ulps comparisons if the signs are not 
the same.

> Those two floats differ
> by precisely 2 units in the last place, and any correct implementation
> should report that.  It's not hard to write code that deals correctly with
> opposite signs.

How do you deal with cases where one number is normalised and the other 
is denormalised? E.g. I think most people would consider these two 
numbers to be close together:

py> to_ulps(2.2250738585072014e-308) - to_ulps(1.1125369292536007e-308)
2251799813685248



-- 
Steve


More information about the Python-ideas mailing list