2

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   :(
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
ibra
  • 1,164
  • 1
  • 11
  • 26
  • I suspect that it's rounding the result 0.09999999999999998 to 15 significant figures – Ben Grossmann Feb 10 '22 at 21:23
  • Does this answer your question? [Why does the floating-point value of 4*0.1 look nice in Python 3 but 3*0.1 doesn't?](https://stackoverflow.com/questions/39618943/why-does-the-floating-point-value-of-40-1-look-nice-in-python-3-but-30-1-doesn) -- "Python tries to find the shortest string that would round to the desired value..." – John Kugelman Feb 10 '22 at 21:25
  • 1
    to print float value with more decimal places try `format(0.1,'.17f')` which shows '0.10000000000000001' or use Decimal class; e.g. `Decimal.from_float(0.1)` – CodeMonkey Feb 10 '22 at 21:26
  • http://weitz.de/ieee/ is a nice tool to see how double precision arithmetic works under the hood – Pranav Hosangadi Feb 10 '22 at 21:32
  • 1
    By the way, `0.1` and `1-0.9` yield slightly different values: `0.1000000000000000055511151231257827021181583404541015625` vs. `0.09999999999999997779553950749686919152736663818359375`. `0.1` can only represent one of them exactly (the first). The other must by necessity be displayed with a bunch of unsightly decimal digits. – John Kugelman Feb 10 '22 at 21:36
  • @JohnKugelman , thank you very much, this is the response that I am looking for. I understand know. `0.1` and `1-0.9` doesn't have the same value, and it is the same for `0.3` and `1-0.7`. The response is combined by the response given in the link [duplicate] + your explanation. Thank you. – ibra Feb 10 '22 at 21:45

0 Answers0