Sum a list of float numbers in Python

avatar

Borislav Hadzhiev

Last updated: Jul 4, 2022

banner

Photo from Unsplash

Sum a list of float numbers in Python #

Use the map.fsum() method to sum a list of float numbers in Python, e.g. total = math.fsum(list_of_floats). The math.fsum() method returns an accurate sum of the floating-point values in the iterable.

main.py
import math # ✅ sum a list of floating-point numbers list_of_floats = [1.1, 2.2, 3.3] total = math.fsum(list_of_floats) print(total) # 👉️ 6.6 # ------------------------------------- # ✅ sum a list of floats wrapped in strings list_of_floats_2 = ['1.1', '2.2', '3.3'] list_of_floats_2 = list(map(float, list_of_floats_2)) print(list_of_floats_2) # 👉️ [1.1, 2.2, 3.3] total = math.fsum(list_of_floats_2) print(total) # 👉️ 6.6

We used the math.fsum() method to sum a list of floating-point numbers.

The math.fsum function takes an iterable and returns an accurate floating-point sum of the values in the iterable.

main.py
print(math.fsum([.1, .1, .1, .1])) # 👉️ 0.4

The method avoids loss of precision by tracking multiple intermediate partial sums.

To get the sum of a list of float numbers that are wrapped in strings:

  1. Use the map() function to convert each string to a float.
  2. Pass the result to the math.fsum() method.
  3. The math.fsum() method will return the sum of the float numbers in the iterable.
main.py
import math list_of_floats_2 = ['1.1', '2.2', '3.3'] list_of_floats_2 = list(map(float, list_of_floats_2)) print(list_of_floats_2) # 👉️ [1.1, 2.2, 3.3] total = math.fsum(list_of_floats_2) print(total) # 👉️ 6.6

We used the map function to convert each string to a floating-point number.

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The function converts each string to a float by passing them to the float() class.

After we have an iterable of floating-point numbers, we can use the math.fsum() method to get the sum without loss of precision.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.