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

Ben Bacarisse ben.usenet at bsb.me.uk
Fri Nov 19 16:55:27 EST 2021


Chris Angelico <rosuav at gmail.com> writes:

> On Sat, Nov 20, 2021 at 5:08 AM ast <ast at invalid> 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.)

Most people understand what's going on when it's explained to them.  And
I think that being initially baffled is not unreasonable.  After all,
almost everyone comes to computers after learning that 3/10 can be
written as 0.3.  And Python "plays along" with the fiction to some
extent.  0.3 prints as 0.3, 3/10 prints as 0.3 and 0.3 == 3/10 is True.

The language (a language, not Python) could tell you that you were not
getting the value you asked for.  Every 0.3 could come with a warning
that 0.3 can not be represented exactly as a floating point value.  To
avoid the warning, the programmer would write ~0.3 meaning, exactly, the
binary (or whatever the base really is) floating point number closest to
0.3.

-- 
Ben.


More information about the Python-list mailing list