What is math.fsum() in Python?

Python is a high-level programming language that offers various modules that allow for clean and consistent code. The math module provides a range of mathematical functions and constants that make operations straightforward. One such function is math.fsum(), which returns the sum of all values in an iterable, such as tuples, arrays, lists, etc.

Syntax

math.fsum(iterable)

Parameters

  • iterable: Any iterable, such as a list, tuple, or array. Returns a TypeError if the values of iterable are not numbers. This parameter is required.

Return value

This function returns the sum of all values in iterable in the form of a float value.

Code example

#import library
import math
#initialize lists
a = [3, 6, 9, 4, 7]
b = [6, 8.44, 15, 5.4]
c = [5.8, 8.3, 2.9, 1.7, 4.3]
#initialize tuples
d = (4, 6, 8, 1, 3)
e = (8.1, 7, 2.00, 2)
f = (6.4, 9.1, 2.5, 6.1)
#print the sums of the iterables
print(a, ':', math.fsum(a))
print(b, ':', math.fsum(b))
print(c, ':', math.fsum(c))
print(d, ':', math.fsum(d))
print(e, ':', math.fsum(e))
print(f, ':', math.fsum(f))

Free Resources