question
I had nothing to do today and calculated it in IDLE 0.1 + 0.2
, and the result surprised me, it was equal to 0.30000000000000004
, Nani? Although there is only one more seventeenth digit after the decimal point 4
, it also made me think deeply. Could it be that I have learned mathematics for so many years in vain?
Let's first look at the results of the program running:
Of course, some students may wonder if this is a bug? So let's do some tests:
The general meaning of this program is that i < 1
at that time , i
it will be added 0.1
, and then each i
value will be printed out. Seeing the results, you should not say that python has so many bugs, it seems that there are unknown secrets in it.
Confused
Unlike integers in Python, Python's floating-point numbers have errors because it uses the IEEE754 standard to store floating-point numbers, so this fundamentally leads to certain precision errors in Python's floating-point numbers. So what is the principle of fixed-point and floating-point numbers? I will not explain it here, but mainly talk about how to solve 0.1+0.2 == 0.3
the problem of how to make it, because it will give you such a result in Python:
>>> 0.1 + 0.2 == 0.3
False
Solving this problem is also very simple, we need to use a decimal
module. The statement used to import modules in Python is import
. The specific procedure is as follows:
After importing decimal
the module, we create objects a and b. Note that the numbers in the brackets are enclosed in single quotes to indicate that they are strings. After that, we can see a + b = 0.3
the result, but at this time, we must pay attention to the fact that it is still not equal a + b
to the direct 0.3
comparison, because they are actually different objects, so we still need to create the object c
, so it a + b == c
is correct.