I tried to compute the following by setting getcontext().prec = 800.
>>> from decimal import *
>>> getcontext().prec = 800
>>> Decimal(22.0) / Decimal ( 10.0) - Decimal ( 0.2 )
Decimal('1.999999999999999988897769753748434595763683319091796875')
>>>
But the expected result is 2. Where am I doing wrong?
When you construct a Decimal from a floating-point number, you get the exact value of the floating-point number, which may not precisely match the decimal value because that's how floating-point numbers work.
If you want to do precise decimal arithmetic, construct your Decimal objects from strings instead of floating-point numbers:
>>> Decimal('22.0') / Decimal('10.0') - Decimal('0.2')
Decimal('2.0')
Pass strings to the Decimal constructor instead of floats: Decimal('0.2') gives the result you expect, Decimal(0.2) doesn't.
This is because:
If value is a float, the binary floating point value is losslessly converted to its exact decimal equivalent. This conversion can often require 53 or more digits of precision. For example, Decimal(float('1.1')) converts to Decimal('1.100000000000000088817841970012523233890533447265625').
https://docs.python.org/3/library/decimal.html#decimal.Decimal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With