How To Properly Sum Numbers in Python
Avoid floating point inaccuracies with fsum()
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 = 0for n in nums:
total += nprint(total) # 0.30000000000000004
print(sum(total)) # 0.30000000000000004
To overcome this challenge, we’ll be importing the native math library.
Importing the Math Library
Let’s start by importing the math library at the top of our Python file.import math
Note: this will import the math library in its entirety. If you want to be more surgical, then explicitly import the fsum() function.from math import fsum
Using the fsum() Function
The fsum() function will behave very similarly to the always available sum() function with the exception that it corrects for floating point inaccuracies. To use either function, simply pass an iterable (tuple, list) to the function.from math import fsumnums = [0.1, 0.1, 0.1]print(sum(nums)) # 0.30000000000000004
print(fsum(nums)) # 0.3
There’s not much more to this simple yet effective solution for floating point addition in Python. If you’re interested in a deeper explanation of fsum() then check out the official Python documentation.
Thanks for reading. Please leave your experiences, questions, and comments below!