python / cpython

The Python programming language
https://www.python.org
Other
63.49k stars 30.41k forks source link

Error in floor division #126872

Closed Sx4DoW closed 1 hour ago

Sx4DoW commented 1 hour ago

Bug report

Bug description:

print(8 // 0.2) print(8 / 0.2)

Expected output: 40.0 40.0

Output: 39.0 40.0

why on earth does 8 // 0.2 return 39?

CPython versions tested on:

3.11

Operating systems tested on:

Windows

ZeroIntensity commented 1 hour ago

Floor division

rishi93 commented 1 hour ago

Might help to read about IEEE 754.

0.2 is not exactly 0.2 in binary representation. It's a bit more, that's why the result comes out to 39.9999 something, and the floor of that is 39.

To get the behaviour that you're expecting, you should use decimal.Decimal

JelleZijlstra commented 1 hour ago

See https://docs.python.org/3/faq/design.html#why-are-floating-point-calculations-so-inaccurate .