How To Properly Sum Numbers in Python

Avoid floating point inaccuracies with fsum()

Jonathan Hsu
Code 85

--

One of the first eye-blinking, brow furrowing experiences when learning Python is an inevitable floating point inaccuracy. We’d expect a computer to be precise and “get math right,” but it’s not so simple.

The Problem with Decimal Arithmetic

Let’s try and add 0.1 together three times and demonstrate the problem.

total = 0.1 + 0.1 + 0.1
print(total) # 0.30000000000000004

To make sense of this, we need to understand (and accept) that floating point arithmetic is used to store decimal values.

What is Floating Point Arithmetic?

Without getting too deep, the takeaway is that Python uses formulas to store decimals and this leads to occasional inaccuracies.

The same discrepancy comes up when we try to manually add our values in a loop or use the sum() function.

nums = [0.1, 0.1, 0.1]
total = 0

--

--