Why print (0.3) prints 0.3, not 0.30000000000000004

So, I think that I basically understand how floating point works and why we cannot have “accurate” results for some operations.

I was confused by this SO question , where @ MikeMüller offers rounding.


My understanding is as follows. If we write decimals, it will look like this:
1000 100 10 1 . 1/10 1/100 1/1000

In binary form, it will look like this:
8 4 2 1 . 1/2 1/4 1/8

Thus, we store 0.5 or 0.25 or 0.125 exactly in memory, but not, for example, 0.3

So why python prints the following:

print(0.1)
print(0.2)
print(0.3)
print(0.1 + 0.2)

>>>0.1
>>>0.2
>>>0.3
>>>0.30000000000000004

I think he should output

>>>0.1
>>>0.2
>>>0.30000000000000004
>>>0.30000000000000004

Where am I mistaken?


? , 0,1 + 0,2!= 0,3. !

+4
3

, 0.1 0.2 . :

>>>print("%.20f" % (0.1+0.2))
0.30000000000000004441

>>>print("%.20f" % 0.3)
0.29999999999999998890

>>>print(0.29999999999999998890)
0.3

, Python , , 0.3 0.3, 0.1 + 0.2.

Python:

, , . , 0.1 0.10000000000000001 0.1000000000000000055511151231257827021181583404541015625 3602879701896397 / 2 ** 55. , eval(repr(x)) == x.

, Python repr() 17 , 0.10000000000000001. Python 3.1, Python ( ) 0.1.

+9

Python 3,

, , . , 0,1 0,10000000000000001 0,1000000000000000055511151231257827021181583404541015625 3602879701896397/2 ** 55. , eval (repr (x) ) == x.

, Python repr() 17 , 0.10000000000000001. Python 3.1, Python ( ) 0,1.

0.3, , , . 0.1 + 0.2 , 0.30000000000000004.

+1

, , . , , .

, 0.30000000000000004 0,3.

, , . , 1e + 6. , .

-1

Source: https://habr.com/ru/post/1627274/


All Articles