0

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:

enter image description here

I am not sure if there are clear answers to why these occur, but how can I avoid these inaccuracies in Python? Thanks.

Jeremy
  • 849
  • 6
  • 15
  • 1
    It's not inaccuracies in Python. It is a consequence of the way floating-point works in your (and everyone else's) computer. And it makes no sense to print a float to 40 significant digits because the float datatype has a precision of 53 bits that can only represent 16-17 decimal digits. If you need more accuracy than that then consider using module `mpmath`. – BoarGules Jun 10 '21 at 14:52
  • This is only some of the examples you can see same stuff happening with trignometric results too, the best and simplest way I came across was to just round to an amount of digits that is needed – BoredRyuzaki Jun 10 '21 at 14:52
  • To avoid inaccuracies, just use the fractions module - https://docs.python.org/3/library/fractions.html – Tom McLean Jun 10 '21 at 14:54
  • Example: import fractions print(float(fractions.Fraction(numerator=100000000000000000000000, denominator=2))) Out[433]: 5e+22 – Tom McLean Jun 10 '21 at 14:56
  • Thanks for all your above comments! – Jeremy Jun 10 '21 at 15:01

0 Answers0