Precision for equality of two floats?

Mike Meyer mwm at mired.org
Mon Nov 28 18:35:16 CET 2005


Anton81 <berrybear at gmx.net> writes:
> When I do simple calculation with float values, they are rarely exactly
> equal even if they should be. What is the threshold and how can I change
> it?

Implementation dependent, because floats use an underlying C type, and
there's no portable way to do that.

> 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? 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).

DSepending on why you need it, you might consider using decimals
(introduced in 2.4) instead of floats.

         <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
 



More information about the Python-list mailing list