python math.fsum()方法,求iterable对象元素和

math.fsum()方法

python标准库math模块中的fsum()方法,可以用于求和python可迭代iterable(比如列表list、元组tuple、集合set等)等对象中的元素之和,其中的各个元素应该是数值类型real number,否则python可能抛出TypeError。


fsum()语法

fsum(seq, /)

python源码对fsum()方法的介绍:

    Return an accurate floating point sum of values in the iterable seq.
    
    Assumes IEEE-754 floating point arithmetic.

参数

参数描述
seqpython序列,iterable可迭代对象,如tuple、list、set等

返回值

python float类型值。


math.fsum()实例代码

>>> import math
>>> list1 = list(range(11))
>>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> math.fsum(list1)
55.0 #返回值为float类型
>>> list1[10] = 'a' #将list1中索引为10的元素修改成字符串
>>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a']
>>> math.fsum(list1) #再次调用fsum()方法,python抛出TypeError,并提示must be real number
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be real number, not str

全栈后端 / Python库 :









Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.