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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.