Unexpected behaviour of math.floor, round and int functions (rounding)

Chris Angelico rosuav at gmail.com
Tue Nov 23 11:08:12 EST 2021


On Wed, Nov 24, 2021 at 3:04 AM ast <ast at invalid> wrote:
>
> Le 19/11/2021 à 21:17, Chris Angelico a écrit :
> > On Sat, Nov 20, 2021 at 5:08 AM ast <ast at invalid> wrote:
> >>
> >> Le 19/11/2021 à 03:51, MRAB a écrit :
> >>> On 2021-11-19 02:40, 2QdxY4RzWzUUiLuE at potatochowder.com wrote:
> >>>> On 2021-11-18 at 23:16:32 -0300,
> >>>> René Silva Valdés <rene.silva.valdes at gmail.com> wrote:
> >>>>
>
> >>
> >>   >>> 0.3 + 0.3 + 0.3 == 0.9
> >> False
> >
> > That's because 0.3 is not 3/10. It's not because floats are
> > "unreliable" or "inaccurate". It's because the ones you're entering
> > are not what you think they are.
> >
> > When will people understand this?
> >
> > (Probably never. Sigh.)
> >
> > ChrisA
> >
>
> I posted that to make people aware of danger of float comparison,
> not because I was not understanding what happened.

And I posted to show that equality is not the problem, and that float
comparison is not dangerous.

> We can see there is a difference on the lsb, due to rounding.
>
>  >>> (0.3+0.3+0.3).hex()
> '0x1.cccccccccccccp-1'
>  >>> 0.9.hex()
> '0x1.ccccccccccccdp-1'
>  >>>
>
> An isclose() function is provided in module math to do float
> comparison safely.
>
>  >>> math.isclose(0.3+0.3+0.3, 0.9)
> True

This is why isclose() was so controversial: it is very very easy to
misuse it. Like this.

ChrisA


More information about the Python-list mailing list