Python fsum

The Python fsum math function is used to calculate and return the sum of iterates (Tuples and Lists). In this section, we show how to use the fsum function with an example.

The syntax of the Python math fsum Function is

math.fsum(Iterators);
  • If the number argument is a positive or negative number, the fsum function calculates and returns the sum of iterated (Tuples and Lists).
  • If the number argument is not a number, it returns TypeError.

Python fsum Function Example

The fsum function calculates and returns the sum of iterates. In this Python example, we are going to return the sum of iterates for different data types and display the output.

import math

Tup = (10, 20, 12, -40 , 50) # Tuple Declaration
Lis = [-98, 32, -39, -42 , 15] # List Declaration

print('Calculating SUM of Tuple Item = %.2f' %math.fsum(Tup))
print('Calculating SUM of Tuple Item = %.2f' %math.fsum(Lis))

print('Calculating SUM of Tuple Items Directly = %.2f' %math.fsum((1, 2, 3, 4, 5)))
print('Calculating SUM of List Items Directly = %.2f' %math.fsum([10, 20, 30, 40]))

print('SUM of Decimal Tuple Items Directly = %.2f' %math.fsum((1.25, 2.45, 3.2, 4, 5.95)))
print('SUM of Decimal List Items Directly = %.2f' %math.fsum([2.45, 20.24, 3.95, 4.59]))

print('SUM of List of String Items Directly = %.2f' %math.fsum(['a', 'b', 'c', 'd']))
Python fsum function Example

Last, We tried this Math function on a List of String values. As we said before, Python returns TypeError as output.