Precision for equality of two floats?

Fredrik Lundh fredrik at pythonware.com
Mon Nov 28 10:57:29 EST 2005


"Anton81" wrote:

> When I do simple calculation with float values, they are rarely exactly
> equal even if they should be. What is the threshold

    http://www.lahey.com/float.htm
    http://docs.python.org/tut/node16.html

> and how can I change it?

you cannot.

> e.g. "if f1==f2:" will always mean "if abs(f1-f2)<1e-6:"

use your own equal function, e.g.

    def equal(a, b):
        return abs(a - b) < 1e-6

    if equal(f1, f2):
        ...

(see the "safe comparision" section of the lahey.com paper
for better ways to test for "approximate equality")

</F>






More information about the Python-list mailing list