Float precision and float equality

Raymond Hettinger python at rcn.com
Sat Dec 5 16:37:28 EST 2009


On Dec 5, 12:56 pm, Mark Dickinson <dicki... at gmail.com> wrote:
> On Dec 5, 8:25 pm, Raymond Hettinger <pyt... at rcn.com> wrote:
>
> > 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().
>
> Can you explain how this would work?  I'm imagining a test
> something like:
>
> if round(x, 6) == round(y, 6): ...
>
> but that still would end up missing some cases where x and y
> are equal to within 1ulp, which presumably isn't what's wanted:

   if not round(x - y, 6): ...


Raymond




More information about the Python-list mailing list