Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve floating point error?

I have looked up online regarding python's floating point arithmetic limitation and seems like the easiest way to solve the problem is to use decimal module. For instance, I tried the below code and it gave me the perfect 0.8 answer.

from decimal import Decimal
Decimal('4') - Decimal('3.2')

However, when I try to incorporate this method into an arithmetic that involves list, the method failed.

from decimal import Decimal
number = [3.2, 1.1]
Decimal('4') - Decimal('number[0]')

This gives me an "InvalidOperation" error. Then I tried

from decimal import Decimal
number = [3.2, 1.1]
Decimal('4') - Decimal(number[0])

This compiles but gives me Decimal('0.7999999999999998223643160600') instead of 0.8

So can anyone please tell me how to solve such a problem? (either use Decimal or any other methods).

Thanks in advance!

like image 236
vivi11130704 Avatar asked Feb 27 '26 15:02

vivi11130704


2 Answers

Pass in a string argument to Decimal to get the expected behavior. In your example, you're passing the floating point number 3.2 instead of the string '3.2'

number = [ '3.2', '1.1' ]
Decimal('4') - Decimal(number[0])

This returns:

Decimal('0.8')
like image 59
jdigital Avatar answered Mar 02 '26 06:03

jdigital


The reason Decimal('4') is specified with '4' in string form is because when an instance of the Decimal class in Python is instantiated with a string it is required to "conform to the decimal numeric string syntax." A string like 'number[0]' doesn't represent a number, and a malformed string is expected to raise an InvalidOperation exception.

Something like Decimal('4') - Decimal('3.8') isn't technically floating point but will get you an exact answer. Floating point is a bit more complicated than arithmetic as is commonly understood with decimal points, and won't be perfectly precise.

It may help to take a look at the documentation for the Decimal class here (https://docs.python.org/3.6/library/decimal.html), and this write-up about floating point operations here (https://docs.python.org/3/tutorial/floatingpoint.html).

like image 40
Jackie H Avatar answered Mar 02 '26 04:03

Jackie H



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!