Home » Python

math.fsum() method with example in Python

Python math.fsum() method: Here, we are going to learn about the math.fsum() method with example in Python.
Submitted by IncludeHelp, on April 17, 2019

Python math.fsum() method

math.fsum() method is a library method of math module, it is used to find the sum (in float) of the values of an iterable, it accepts an iterable object like an array, list, tuple, etc (that should contain numbers either integers or floats), and returns sum in float of all values.

Note: If an iterable contains anything except the number, the method returns a type error, "TypeError: a float is required".

Syntax of math.fsum() method:

    math.fsum(iterable)

Parameter(s): iterable – an iterable object like list, array, tuple, etc.

Return value: float – it returns a float value that is the sum (in float) of all values of the given iterable.

Example:

    Input:
    a = [10, 20, 30, 40, 50]    # list of integers

    # function call
    print(math.fsum(a))

    Output:
    150.0

Python code to demonstrate example of math.fsum() method

# Python code demonstrate example of 
# math.fsum() method
import math

# iterable objects
a = range(10)   # a range object (0,10)
b = [10, 20, 30, 40, 50]    # list of integers
c = [10, 20, 30.30, 40, 50.0]   # list of integers & floats
d = [10.20, 30.40]  # list of floats
e = (10, 20, 30, 40.50) # tuple

# printing sum of all values of the iterable objects
print("fsum(a): ", math.fsum(a))
print("fsum(b): ", math.fsum(b))
print("fsum(c): ", math.fsum(c))
print("fsum(d): ", math.fsum(d))
print("fsum(e): ", math.fsum(e))

Output

fsum(a):  45.0
fsum(b):  150.0
fsum(c):  150.3
fsum(d):  40.599999999999994
fsum(e):  100.5


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.