Float precision and float equality

Raymond Hettinger python at rcn.com
Sat Dec 5 15:25:48 EST 2009


On Dec 5, 7:37 am, 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?

Short answer: use round().
Less short answer:  use Decimal with a high precision and then round()
or quantize.
Long answer:  the amount of error depends on the calculation and the
scale of the inputs; some calculations potentially propagate tiny
errors to the point where they become large enough to overpower the
signal in your data (e.g. the Lorentz equation or some other chaotic
sequence).


Raymond



More information about the Python-list mailing list