1

The following loop adds 0.1 ten times and ends up printing "0.9999999999999999 is not 1.0":

x = 0.0
for i in range(10):
    x = x + 0.1
    
if x == 1.0:
    print(x, '= 1.0')
else:
    print(x, 'is not 1.0')

I understand this is because 0.1 cannot be represented exactly as a binary fraction, but why is the result less than 1 when the floating point representation of 0.1 is greater than 0.1 (i.e. 0.1000000000000000055511151231257827021181583404541015625)?

I tried printing the actual value of x at each iteration using print(format(x, ".50f")) as follows:

x = 0.0
for i in range(10):
    x = x + 0.1
    print(format(x, ".55f"))

0.1000000000000000055511151231257827021181583404541015625
0.2000000000000000111022302462515654042363166809082031250
0.3000000000000000444089209850062616169452667236328125000
0.4000000000000000222044604925031308084726333618164062500
0.5000000000000000000000000000000000000000000000000000000
0.5999999999999999777955395074968691915273666381835937500
0.6999999999999999555910790149937383830547332763671875000
0.7999999999999999333866185224906075745820999145507812500
0.8999999999999999111821580299874767661094665527343750000
0.9999999999999998889776975374843459576368331909179687500

But now I don't understand where the 0.5 comes from. Why does adding 0.4000000000000000222044604925031308084726333618164062500 + 0.1000000000000000055511151231257827021181583404541015625 give us exactly 0.5?

user51462
  • 1,658
  • 2
  • 13
  • 41
  • 1
    [This answer](https://stackoverflow.com/a/47367873/4177009) seems relevant. – Ture Pålsson Jul 02 '22 at 06:53
  • The values you show are decimal *approximations* of the binary values really used in the calculations, so there's no wonder that adding them doesn't give the same result as adding the real values. – Thierry Lathuille Jul 02 '22 at 07:13

0 Answers0