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

ast ast at invalid
Tue Nov 23 06:53:56 EST 2021


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.

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


More information about the Python-list mailing list