Python: Floating-Point Arithmetic: Issues and Limitations

Came across an error handling a workflow for finance for the first time

Kahhow
1 min readOct 7, 2024

Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. For example, the decimal fraction 0.625 has value 6/10 + 2/100 + 5/1000, and in the same way the binary fraction 0.101 has value 1/2 + 0/4 + 1/8. These two fractions have identical values, the only real difference being that the first is written in base 10 fractional notation, and the second in base 2.

Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.

Source: Python Documentation

How to fix?

Import the library decimal then call the function, example below:

from decimal import *
>>> getcontext().prec = 6
>>> Decimal(1) / Decimal(7)
Decimal('0.142857')
>>> getcontext().prec = 28
>>> Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')

Users can define precision up to 28 decimal points (if you ever need that precision for whatever reason).

See Python Decimal Library Documentation here

--

--

Kahhow

Educator interested in data science, dance and full stack development