The Python math.fsum() function takes a list of floating point numbers, and sums them up (totals/adds them all together). Here’s how to use it, with examples.
Summing/Totalling/Adding Numbers
The concept of summing numbers is simple – take the numbers you wish to get the total of, and add them all together.
1 + 2 + 3 = 6
It’s basic arithmetic that you’ll use daily when writing computer software in any language.
Summing Numbers in Python
The sum() function in Python sums numbers. It’s a built-in function, which can be used anywhere in your code without having to import any dependencies.
BUT
You should NOT use it to sum floating point numbers when high accuracy is required.
Floating Point Precision Errors When Using sum()
Otherwise, you are likely to run into floating point precision errors:
sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) # results in 0.9999999999999999
Above, an inaccurate result is returned by the sum() function – the answer should be 1, not 0.9999999999999999. math.fsum() will give the correct result:
import math math.fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) # results in 1.0
math.fsum() Syntax
The syntax for the math.fsum() function is as follows:
import math math.fsum(ITERABLE)
Note that:
- ITERABLE can be any Python iterable, containing numerical values
- Usually, this is a list of numbers
- Note that the math library must be imported into your Python script before math.fsum() can be called
math.fsum() Example
Below, a list of floating point numbers is summed:
import math numberList = [2.1, 6.43, 18.3, 3.0] numberSum = math.fsum(numberList)