Python math.fsum() – Sum of Values in Iterable

Python math.fsum()

math.fsum(x) function returns the sum of items in the iterable x.

Syntax

The syntax to call fsum() function is

math.fsum(x)

where

ParameterRequiredDescription
xYesAn iterable.

Examples

1. Sum of numbers in a list

In the following program, we take a list in x, and find the sum of items in this list, using math.fsum() function.

Python Program

import math

x = list([2.4, 5.1, 6.7])
result = math.fsum(x)
print('fsum(x) :', result)
Run Code Copy

Output

fsum(x) : 14.2

2. Sum of numbers in a tuple

In the following program, we take a tuple in x, and find the sum of items in this tuple, using math.fsum() function.

Python Program

import math

x = tuple([2.4, 5.1, 6.7])
result = math.fsum(x)
print('fsum(x) :', result)
Run Code Copy

Output

fsum(x) : 14.2

3. Sum of numbers in a range

In the following program, we take a range object in x, and find the sum of items in this range, using math.fsum() function.

Python Program

import math

x = range(5)
result = math.fsum(x)
print('fsum(x) :', result)
Run Code Copy

Output

fsum(x) : 10.0

4. math.fsum() when there is/are infinity as item in the list

In the following program, we check what math.fsum() returns when there is one or more infinity values, and the rest float/integral values, in the iterable.

Python Program

import math

x = [math.inf, 5, 3.2]
result = math.fsum(x)
print('fsum(x) :', result)
Run Code Copy

Output

fsum(x) : inf

5. math.fsum() when there is/are nan as item in the list

In the following program, we check what math.fsum() returns when there is at least one nan value in the iterable.

Python Program

import math

x = [math.nan, 5, 3.2]
result = math.fsum(x)
print('fsum(x) :', result)
Run Code Copy

Output

fsum(x) : nan

Summary

In this Python Math tutorial, we learned the syntax of, and examples for math.fsum() function.

Related Tutorials

Code copied to clipboard successfully 👍