How To Stop Floating Point Arithmetic Errors in Python
We expect precision, consistency, and accuracy when we code. After all, it’s a computer doing the work. But your arithmetic may have been off the entire time and you didn’t even know.

If you’ve experienced floating point arithmetic errors, then you know what we’re talking about. If you’re unsure what that means, let’s show instead of tell.

print(1.1 * 3) # 3.3000000000000003

This happens because decimal values are actually stored as a formula and do not have an exact representation.

We’re going to go over a solution to these inconsistencies, using a natively available library called Decimal.

Learn to Use the Decimal Library

According to the official Python documentation:

The decimal module provides support for fast correctly-rounded decimal floating point arithmetic.

So how do we go about using this readily available tool? Let’s start by importing the library. There are multiple components to import so we’ll use the * symbol.

from decimal import *

Next, we’ll use the Decimal() constructor with a string value to create a new object and try our arithmetic again.

print(Decimal('1.1') * 3) # 3.3

Make sure to use a string value, because otherwise the floating point number 1.1 will be converted to a Decimal object, effectively preserving the error and probably compounding it even worse than if floating point was used.
['Jonathan Hsu']
['Coding', 'Programming', 'Python', 'Data Science', 'Technology']