I come across some weird calculations in Python. I checked Python official documents and tutorials on decimal precessions and stuffs. But I just do not understand how to get the below calculations correctly:
# precisions with small numbers in Python
a = 0.1
b = 0.1
c = 0.1
d = a+b+c
# quickly print out "d"
print(d)
# now show "d" with 40 digits
print(f'{d:.40f}')
And
# now reverse the above calculation
e = d - (a+b+c)
f = d - (0.1+0.1+0.1)
g = d - 0.1 - 0.1 - 0.1
print(f'{e:.40f}')
print(f'{f:.40f}')
print(f'{g:.40f}')
And
# calculation of this huge number is wrong
number1 = 100000000000000000000000/2
print(f'{number1:f}')
# but calculating a smaller number would be fine
number2 = 100000/2
print(f'{number2:f}')
The results on my PC are here:
I am not sure if there are clear answers to why these occur, but how can I avoid these inaccuracies in Python? Thanks.