I know rounding errors happen in floating point arithmetic but can somebody explain the reason for this one:
>>> 8.0 / 0.4 # as expected
20.0
>>> floor(8.0 / 0.4) # int works too
20
>>> 8.0 // 0.4 # expecting 20.0
19.0
This happens on both Python 2 and 3 on x64.
As far as I see it this is either a bug or a very dumb specification of //
since I don't see any reason why the last expression should evaluate to 19.0
.
Why isn't a // b
simply defined as floor(a / b)
?
EDIT: 8.0 % 0.4
also evaluates to 0.3999999999999996
. At least this is consequent since then 8.0 // 0.4 * 0.4 + 8.0 % 0.4
evaluates to 8.0
EDIT: This is not a duplicate of Is floating point math broken? since I am asking why this specific operation is subject to (maybe avoidable) rounding errors, and why a // b
isn't defined as / equal to floor(a / b)
REMARK: I guess that the deeper reason why this doesn't work is that floor division is discontinuous and thus has an infinite condition number making it an ill-posed problem. Floor division and floating-point numbers simply are fundamentally incompatible and you should never use //
on floats. Just use integers or fractions instead.