Python math.fsum() Method

Python math.fsum() method is used to calculate the sum of all elements in any iterable such as  arrays, tuples, lists, etc.

Syntax

import math
math.fsum(iterable)

Parameter

iterable(required): An iterable (like an array, list or tuple) containing numbers (integers or floating point numbers) that you want to sum up.

Return Value

Returns the sum of the elements in an iterable or range as a floating-point number.

If the iterable contains non-numeric elements, it raises a TypeError.

Visual Representation

Visual Representation of Python math.fsum() Method

Example 1: How to Use math.fsum() Method

#importing math library
import math

# Summing numbers from 0 to 4
print(math.fsum(range(5)))

# Summing a list of numbers
print(math.fsum([2,4,6,8,10]))

# Summing list of floating point numbers
print(math.fsum([2.1,4.1,6.5,8.7,10.9]))

Output

10.0
30.0
32.3

Example 2: Passing an array

Visual Representation of Passing an array

import math
# Create a NumPy array
arr = [5,10,15,20,25]

# sum the elements of the array
print(math.fsum(arr))

Output

75.0

Example 3: Passing a tuple

Visual Representation of Passing a tuple

import math

# Define a tuple of numbers
numbers_tuple = (2.2, 4.4, 6.6, 8.8, 10.5)

# sum the elements of the tuple
print(math.fsum(numbers_tuple))

Output

32.5

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.