Search code examples
pythondecimalprecisionbignumarbitrary-precision

Python 3 decimal module calculation reversability


I am trying to implement a reversible physics engine so I have decided to use the decimal module. So this obviously works.

>>> from decimal import *
>>> a = Decimal('1')
>>> b = Decimal('0.82')
>>> a = a*b/b
>>> print(a)
1

However, when this operation is repeated, i.e. "multiply 100 times and then divide 100 times", the result does not precisely equal to a again.

>>> for _ in range(100):
...     a = a*b
...
>>> for _ in range(100):
...     a = a/b
...
>>> a
Decimal('0.9999999999999999999999999965')

Am I doing something wrong? Is it possible to do these calculations reversably, so that I get the initial result?


Solution

  • Decimal doesn't have infinite precision. You can increase its precision if you're finding it too inaccurate.

    from decimal import *
    getcontext().prec = some larger number