Python told me 0.1+0.2! =0.3, so many years of mathematics learning for nothing?

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:

insert image description here

Of course, some students may wonder if this is a bug? So let's do some tests:

insert image description here

The general meaning of this program is that i < 1at that time , iit will be added 0.1, and then each ivalue 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.3the 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 decimalmodule. The statement used to import modules in Python is import. The specific procedure is as follows:

insert image description here

After importing decimalthe 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.3the result, but at this time, we must pay attention to the fact that it is still not equal a + bto the direct 0.3comparison, because they are actually different objects, so we still need to create the object c, so it a + b == cis correct.

Guess you like

Origin blog.csdn.net/m0_46376148/article/details/108509828