Why 0.2+0.1 is not equal to 0.3 in Python
Everyone please see the python program code below:
print(0.2+0.1)
Guess what the run results in, is it 0.3?
NoNoNo!
Take a look at the results of the run:
0.30000000000000004
Why is it 0.30000000000000004?
floating point operation
This is because in computers, floating point operations are also converted to binary first
1. How floating point numbers are converted to binary:
(1) Integer part: divide by 2, take out the remainder, continue to divide the quotient by 2 until you get 0, and take out the remainder in reverse order.
(2) Decimal part: multiply by 2, then take out the whole number part, continue to multiply the remaining decimal part by 2, then take the whole number part again, and so on until the decimal part is zero.
If it is never zero, retain a sufficient number of decimal places as required and do 0 rounding to the last place. Arrange the removed integers in order.
2. Conversion of 0.2 to binary: (decimal places only)
0.2 × 2 = 0.4 take 0
0.4 × 2 = 0.8 take 0
0.8 × 2 = 1.6 take 1
0.6 × 2 = 1.2 take 1
0.2 × 2 = 0.4 take 0
0.4 × 2 = 0.8 take 0
0.8 × 2 = 1.6 take 1
…
So 0.2 is converted to a floating point number of 0.001100110011... (0011 infinite loop) 0.1 is converted to binary:
Similarly 0.1 is converted to a floating point number as 0.0001100110011... (0011 infinite loop)
0.2+0.1
Since neither 0.2 nor 0.1 are definite numbers in a computer, but are approximations, the values they get after floating-point operations (pairwise ordering, trailing operations, specification processing, rounding, and overflow processing) are also approximations, rounded by the computer. So the result is 0.30000000000000004
P.S. Realization of 0.1 + 0.2 == 0.3
There is a module decimal in python that solves the 0.1+0.2!=0.3 problem.
The decimal module provides a Decimal data type for floating-point calculations, which is more accurate than the built-in binary floating-point calculations.
Simple usage: pass Decimal integer or string type to decimal, but not floating point data (floating point data is inherently inaccurate)
summarize
to this article on why Python 0.2 + 0.1 is not equal to 0.3 of the article is introduced to this, more related Python 0.2 + 0.1 is not equal to 0.3 content, please search for my previous posts or continue to browse the following related articles I hope that you will support me more in the future!