Float precision and float equality
dickinsm at gmail.com
Sat Dec 5 17:46:55 CET 2009
On Dec 5, 3:37 pm, Anton81 <gerenu... at googlemail.com> wrote:
> I'd like to do calculations with floats and at some point equality of
> two number will be checked.
> What is the best way to make sure that equality of floats will be
> detected, where I assume that mismatches beyond a certain point are
> due to truncation errors?
Well, it depends a lot on the details of the application, but
a good general scheme is to allow both a fixed relative error
and an absolute error, and to assert that your two values are
'nearly equal' if they're within *either* the relative error *or*
the absolute error. Something like, for example:
def almostEqual(expected, actual, rel_err=1e-7, abs_err = 1e-20):
absolute_error = abs(actual-expected)
return absolute_error <= max(abs_err, rel_err * abs(expected))
Then choose the values of rel_err and abs_err to suit your
What sort of calculations are you doing?
More information about the Python-list