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.

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