Python fsum()函数的完整指南

543 阅读2分钟

Python fsum()方法是用来寻找一些范围或迭代器之间的和。不幸的是,fsum()函数在数学库下,要使用这个函数,我们首先要导入数学。

Python fsum()

Python fsum() 是数学模块的一个内置方法,用于查找一个可迭代的值的总和 (以浮点数表示),它接受一个可迭代的对象,如数组、列表元组等 (应该包含整数或浮点数)。它返回所有数值的浮点数。

语法

math.fsum( value )

参数

值可以是一个范围或一个可迭代的对象,如数组、元组。

返回值

fsum()函数返回可迭代值或范围的浮点数之和。fsum()中的'f'代表浮点数。

编程实例

请看下面的代码:

# 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))

输出

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

在这个程序中,我们首先有一个导入的数学库,然后我们从用户那里获得一个输入的整数。之后,我们计算了到该数字为止的所有元素的总和,然后我们打印了该数字。

另一方面,我们接受了一个列表的输入,用户必须用一个空格给所有列表元素。然后我们调用 fsum() 来计算所有列表元素的总和。

例2

请看下面的代码:

# 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))

输出

python3 app.py
55.0
78.0
5.1

总结

Python fsum()是Python数学函数之一,用于计算和返回迭代器的总和,如Tuples和Lists。

另请参见

Python frexp()

Python fmod()

Python 阶乘

Python math.fabs()

Python math copysign()

Python 数学函数

Python math.sqrt()

Python math.floor()