4
>>> 0.03 % 0.01
0.009999999999999998
Why gives this result, the rest of the division being 0?
And also, instead of 3, give:
>>> 0.03 // 0.01
2.0
4
>>> 0.03 % 0.01
0.009999999999999998
Why gives this result, the rest of the division being 0?
And also, instead of 3, give:
>>> 0.03 // 0.01
2.0
14
Exactly for the same reason that 0.1 + 0.7 is 0.7999999999999 and not 0.8.
Which, briefly, boils down to the summary: IEEE 754.
To get around the problem, you need to use the module decimal
:
from decimal import Decimal
a = Decimal('0.03')
b = Decimal('0.01')
print(a % b) # 0.00
print(a // b) # 3
11
Short answer: Precision problems in floating point operations.
Decimal numbers are represented on the computer as decimal fractions. For example, 0.125(10) = 0.001(2)
. Nothing new - but if so, take a look at this short summary in Wikipedia on floating comma.
The problem is when we enter numbers that cannot be easily described by a binary fraction that result in infinite tithes like the case of 1/3 = 0.33(3)
in the decimal system.
Computers do not have an infinite number of bits so they use approximate representations of the numbers they intend to represent. They are very close presentations but they are still not the number in question.
>>> 0.1
0.1000000000000000055511151231257827021181583404541015625
Python (among other languages) can detect these cases and present the user with a "rounded" representation of the user that corresponds to what would be expected:
>>> 1 / 10
0.1
However this does not change the value that is in memory. So, when doing 0.03 % 0.01
is not even to do the rest of the 0.03 by 0.01 division but rather the rest of the 0.03 by 0.01 memory division, resulting in the error you see:
>>> 0.03 % 0.01
0.009999999999999998
Source: The Python Tutorial - Floating-point arithmetic operations: problems and limitations (in English)
Browser other questions tagged python python-3.x floating-point
You are not signed in. Login or sign up in order to post.
Read these references: 1, 2, 3 and 4. Especially in the refs of the answers given here.
– danieltakeshi
Not only in Python, but in any programming language that uses floating points of IEEE 754
– Leonardo Bosquett