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
?