Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "decimal" package gives wrong results

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?

like image 750
young_leamer Avatar asked Jan 29 '26 10:01

young_leamer


2 Answers

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')
like image 82
Dennis Sparrow Avatar answered Feb 01 '26 00:02

Dennis Sparrow


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

like image 34
Joni Avatar answered Jan 31 '26 22:01

Joni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!