AppDividend
Latest Code Tutorials

Python fsum() Function Example

0

Python fsum() is an inbuilt math function that is used to find the sum between some range or iterable. The sum() function is under the math library, so to use this function, we first will have to import math.

Python fsum()

Python fsum() method is a library method of the math module, and 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). It returns the sum in float of all values.

Syntax

math.fsum( value )

Here, the value can be a range or an iterable like an array, tuple.

Return Value

The fsum() function returns the sum of the iterable or range in floating-point number. ‘f’ in fsum() stands for float.

Programming Example

See the following code.

# app.py

#importing math library
import math

#Finding sum of a range first

#taking input from the user
x=int(input("Please enter a range up to which you want to sum: "))

#finding sum of the range using fsum()
print("Sum of the range is: ",math.fsum(range(x)))

#Finding sum of an iterable

#taking input of a list 
print("Please enter array element with space separated integer: ")
arr=list(map(int,input().split(" ")))

#printing all array elements
print("All array elements are: ",arr)

#Finding sum of all the values using fsum()
print("Sum of all elements of the array is: ",math.fsum(arr))

Output

Please enter a range up to which you want to sum: 15
Sum of the range is:  105.0
Please enter the array element with space-separated integer:
1 3 5 7
All array elements are:  [1, 3, 5, 7]
Sum of all elements of the array is:  16.0

In this program, we first have an imported math library, and then we have taken an input integer from the user. After that, we have calculated the sum of all elements up to that number, and then we have printed that.

On the other hand, we have taken input for a list, where the user will have to given all list elements by a space. Then we have called fsum() to calculate the sum of all the list elements.

Example 2

See the following code.

# app.py

import math

# range(11)
print(math.fsum(range(11)))

# Integer list
arr = [11, 46, 21]
print(math.fsum(arr))

# Floating point list
arr = [2.1, 1.1, 1.9]
print(math.fsum(arr))

Output

python3 app.py
55.0
78.0
5.1

Conclusion

Python fsum() is one of the Python Math function that is used to calculate and return the sum of iterators like Tuples and Lists.

See also

Python frexp()

Python fmod()

Python factorial

Python math.fabs()

Python math copysign()

Python math functions

Python math.sqrt()

Python math.floor()

Leave A Reply

Your email address will not be published.

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