+ 12
Error in Python?? 0.1+0.2 not equal 0.3??
I just run the below code with results: 1+1==2 Out[355]: True 0.1+0.1==0.2 Out[356]: True 0.1+0.2==0.3 Out[357]: False Anybody knows what happened?
5 Antworten
+ 41
The problem is that most decimal fractions can't really be represented in binary digits.
If you have an integer like 5 and want to convert it to binary, this is what you do:
[1] x 2^2 = 4
+
[0] x 2^1 = 0
+
[1] x 2^0 = 1
So, 5 is 101 in binary.
With decimal places, it is basically the same procedure, but you use reciprocals of 2 (1/2, 1/4, 1/8 etc.). For example, 0.625 would be:
[1] x 1/2 = 1/2
[0] x 1/4 = 0
[1] x 1/8 = 1/8
So, .625 would be .101 (in reality, it's a little more complex).
Unfortunately, this won't really work for most decimal fractions.
0.1 would be something like:
[0] x 1/2 = 0
[0] x 1/4 = 0
[0] x 1/8 = 0
[1] x 1/16 = 1/16
[1] x 1/32 = 1/32
[0] x 1/64 = 0
[0] x 1/128 = 0
[1] x 1/256 = 1/256
=> .00011001
1/16 + 1/32 + 1/256 = 0.09765625, which is very close to 0.1, but it is not equal.
The more bytes you use to represent the decimal fraction, the closer you get to the actual value. But it will never be equal.
That's why if you calculate 0.1 + 0.2, the result will be something like 0.296875 instead of 0.3 and thus (from Python's point of view) not equal to 0.3.
+ 4
In Java, for instance, we have a BigDecimal type which can calculate accurately, at the expense of performance. Floating point errors aren't an issue for something like graphics rendering, where the tiny error in a coordinate won't be noticeable, but if dealing with finance that requires accuracy there is probably a more suitable data type you can use
+ 2
floating point error. Use the search bar :p
+ 1
thank you! very clear now. I just wonder though how this can be resolved? as this is fundamental and can lead to serious error
+ 1
so there is an alternative comparison operator other than ==, that is weaker and allow range? do we have such a thing in python?