Precision for equality of two floats?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Mon Nov 28 22:58:35 CET 2005


On Mon, 28 Nov 2005 12:35:16 -0500, Mike Meyer wrote:

>> e.g. "if f1==f2:" will always mean "if abs(f1-f2)<1e-6:"
> 
> This is a *bad* idea. What happens if f1=1e-12 and f2=1e-112? Do you
> really want to values that 100 orders of magnitude different to
> compare as equal? 

Sure, if f1 and f2 represent quantities like "average number of people,
in millions", both should be considered as more or less zero. It is a
little hard to justify treating one millionth of a person as a meaningful
figure, no matter how accurate your model for population growth might be.

For the avoidance of confusion, I am *not* suggesting that == for floats
should have any other behaviour other than the one it has now, merely that
the developer rarely wants to use == for comparing floats.

Floating point equality is usually application-specific. Not only do
the floats themselves have only finite resolution, but often you don't
even care about that full resolution since it simply introduces spurious
accuracy not justified by either your model or your data.

> You should use something like "if abs(f1 - f2) <
> abs(f1) * 1e-6" (been a long time since I worried about this; there's
> probably a better version).

Sometimes you want relative differences, sometimes you care about absolute
differences, and sometimes -- very rarely -- you actually want full-blown
bit-for-bit equality.


-- 
Steven.




More information about the Python-list mailing list