0

Why does this code output 25 although I used the decimal module. I tried it on the calculator and it outputted 26.28.

from decimal import *
getcontext().prec = 2

targetPrice = 40
currentPrice = 56.5
winChance = 0.9
stopLoss = 23
lossChance = 0.1

expectancy =100 * abs(((Decimal(targetPrice) -  Decimal(currentPrice)) / Decimal( currentPrice))) *  Decimal(winChance)
print(expectancy)
2
  • You are doing all of your calculations with a precision of 2. This introduces a fair amount of round-off error. Your calculator uses more like 15 decimal places of precision. Not surprisingly, it is more accurate. The decimal module is intended for calculations which are higher precision than a 64-bit float. For some reason you are using it for lower-precision calculations. Commented Oct 6, 2021 at 16:44
  • 1
    Applying Decimal() to floating-point values entirely misses the point of the Decimal module. 0.9, for example, is not a value that can be accurately represented as a float; turning it into a Decimal results in a precise value that isn't quite equal to 0.9. You have to use strings - Decimal('0.9') for example - to produce exact values. Commented Oct 6, 2021 at 16:47

1 Answer 1

2

You're getting inexact results because you're rounding down to two decimal places after every calculation. Your calculator isn't doing that.

With no rounding.

>>> (Decimal(40) - Decimal(56.5)) / Decimal(56.5)
Decimal('-0.2920353982300884955752212389')

With rounding:

>>> (Decimal(40) - Decimal(56.5)) / Decimal(56.5)
Decimal('-0.28')

It only gets worse after that.

Sign up to request clarification or add additional context in comments.

1 Comment

Should we use strings as suggested in @jasonharper's comment under OP?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.