Floating point numbers are not the same as decimal numbers

** Python learning output. ** **

The math module has a .isclose () function. Used when comparing float type numerical values. Whether each is an approximation.

>>> import math
>>> math.isclose(0.1+0.1+0.1, 0.3)
True

As a general premise, computer hardware, including Python, cannot accurately represent floating point numbers. Since it is expressed as a binary fraction, for example, a binary fraction

0.001

Is

0/2 + 0/4 + 1/8

It becomes the value.

However, most decimals cannot be accurately represented as binary fractions, so approximate values are stored.

To get the exact value of the float type, use the float.as_integer_ratio () method. Substituting 3 for x and using this method to express the exact value as a rational number ...

>>> x = 0.3
>>> x.as_integer_ratio()
(5404319552844595, 18014398509481984)
>>> x == 5404319552844595 / 18014398509481984
True
>>> 5404319552844595 / 18014398509481984
0.3

Somehow amazing.

Now substitute 0.1 for x and multiply by 3. Then

>>> x = 0.1
>>> x.as_integer_ratio()
(3602879701896397, 36028797018963968)
>>> 3602879701896397 /  36028797018963968
0.1
>>> 3602879701896397 /  36028797018963968 * 3
0.30000000000000004

like this. Therefore, the conditional expression of 0.1 + 0.1 + 0.1 == 0.3 does not hold.

However, 0.30000000000000004 can be said to be an approximation of 0.3. Therefore, as mentioned above,

>>> import math
>>> math.isclose(0.1+0.1+0.1, 0.3)
True

The .isclose () function returns True.

reference Official Python documentation: 15. Floating Point Arithmetic, Its Problems and Limitations

Recommended Posts

Floating point numbers are not the same as decimal numbers
[Python3] "A // B" and "math.floor (A / B)" are not always the same! ??
Floating point calculation for the awk command
Python open and io.open are the same
Access files in the same directory as the executable
Calculation result after the decimal point in Python