1

I'm learning Python. Maybe this is a silly mistake and not related to Python at all but appreciate some clarity.

I have the following code.

from decimal import Decimal

expense = Decimal('10.00')
v = Decimal('93.93863013698630136986301369')
n = Decimal('46.90520547945205479452054796')
yearly_expense = Decimal('0')

vn = v + n

r1 = expense - yearly_expense + v + n
r2 = expense - yearly_expense + vn

print(r1)
print(r2)

When I execute I get

150.8438356164383561643835617
150.8438356164383561643835616

Note the last digits. Why the 2 numbers are different?

Vahid
  • 1,625
  • 1
  • 18
  • 33
  • 1
    Add return of `decimal.getcontext()` to question, please. – Olvin Roght Dec 28 '22 at 22:38
  • Reproducible on Python 3.10.6, getcontext() returns `Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[InvalidOperation, DivisionByZero, Overflow])` for me. – kaya3 Dec 28 '22 at 22:41
  • 2
    The default precision in the Decimal package is 28 digits. Your input values have 28 digits, and when you combine them the result needs 29 digits. So you're getting roundoff error at the end. – Barmar Dec 28 '22 at 22:41
  • 1
    @kaya3, now set `decimal.getcontext().prec = 30` and try again :) – Olvin Roght Dec 28 '22 at 22:42
  • 1
    see also: https://docs.python.org/3/library/decimal.html – JonSG Dec 28 '22 at 22:45
  • Does this answer your question? [Setting precision in Decimal class Python](https://stackoverflow.com/questions/27638005/setting-precision-in-decimal-class-python) – JonSG Dec 28 '22 at 22:45
  • 2
    You are seeing the fact that with finite precision floating point arithmetic (with or without the `decimal` module addition is sometimes non-associative: `a + (b+c)` and `(a+b)+c` can differ due to round-off error. Changing the precision can take care of a specific instance, but won't change the general phenomenon. – John Coleman Dec 28 '22 at 22:46
  • You can also set the traps[Inexact] in your context to catch this as an exception. – Kenny Ostrom Dec 29 '22 at 01:09

0 Answers0