If 0.1 can't be represented exactly in binary, why does printing it show "0.1" and not "0.09999999999999998"?

Viewed 45

Can you please explain to me how a float number is stored in a variable in python (x=0.1)?

I am confused about storing floating point arithmetic vs storing float.

I do understand that : Floating-point numbers are represented in computer hardware as base 2 (binary) fractions (docs python floatingpoint). Hence, rational numbers (such as 0.1, which is 1/10) whose denominator is not a power of two cannot be exactly represented (stackoverflow floating-point).

From that, I thought that when I store a float number in variable (x=0.1), when I print x, I should get 0.09999999999999998, because in my understanding we can't represent it as 0.1. But, the result shows that x hold 0.1, and I don't know how?

>>> res = 1-0.9   # 1
>>> x=0.1         # 2
>>> res , x
(0.09999999999999998, 0.1)   #  1 vs 2   :(
0 Answers
Related