python - Python 3 中浮点数的准确累积和
问题描述
给定 Python 中的浮点数列表,生成该列表的累积和的最准确方法是什么?
我所说的准确是指对舍入误差具有鲁棒性。
特别是我想了解我是否应该使用list(itertools.accumulate(my_list))
或计算这个列表成对使用math.fsum()
?
Numpy 不是一个选择。
是否itertools.accumulate(my_list)
在内部对浮点数使用准确的求和函数math.fsum()
?
在这种情况下他们有什么区别?
如果可能的话,可以math.fsum
指定为加法函数,itertools.accumulate
这有意义吗?
解决方案
是否
itertools.accumulate(my_list)
在内部对浮点数使用准确的求和函数math.fsum()
?
不,PyNumber_Add
是在itertools 源代码中使用的。PyNumber_Add
是标准添加,就像x + y
在 python中一样
如果可能,可以
math.fsum
指定 initertools.accumulate
作为要使用的加法函数吗?
是的,您可以使用可选func
参数指定它:
import itertools
import math
l = [.1, .2, .3, .4, .5]
list(itertools.accumulate(l, lambda x, y: math.fsum([x, y])))
那有意义吗?
不,如文档中所述,math.fsum
通过跟踪多个中间部分和来避免精度损失
因此,一次只对两个以上的浮点数使用它才有意义:
>>> import math
>>> .1 + .2 + .3 == math.fsum([.1, .2, .3])
False
>>> .1 + .2 == math.fsum([.1, .2])
True
你最喜欢这样的东西:
>>> import math
>>>
>>> l = [.1, .2, .3, .4, .5]
>>> [math.fsum(l[:i+1]) for i in range(len(l))]
[0.1, 0.30000000000000004, 0.6, 1.0, 1.5]