Python math.fsum()

Anonymous contributor's avatar
Anonymous contributor
Published Sep 6, 2024
Contribute to Docs

In Python, the math.fsum() function takes an iterator as an argument and returns the floating-point sum of all the items in the iterator. This function avoids loss of precision by tracking intermediate partial sums.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

math.fsum(iterable)
  • iterable: An iterable (e.g., list, tuple) containing numeric values. This is the sequence of numbers whose sum is to be calculated.

Example

The following example uses math.fsum() to return the accurate floating point sum of the given list:

import math
numbers_list = [1, 1e-1, 1e-2, 1e-3, 1e-4]
print(math.fsum(numbers_list))

The above code gives the following output:

1.1111

Codebyte Example

Run the following example that uses the math.fsum() function to understand its working:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours