给定 Python 中的 float 列表,生成该列表的累积和的最准确方法是什么?
我所说的“准确”是指对舍入误差具有鲁棒性。
特别是我想了解是否应该使用 list(itertools.accumulate(my_list))
或使用 math.fsum()
成对计算此列表?
Numpy 不是一个选项。
是itertools.accumulate(my_list)
在内部对 math.fsum()
这样的 float 使用精确的求和函数还是不?
在这种情况下它们有什么区别?
如果可以的话可以math.fsum
被指定为 itertools.accumulate
中的加法函数这有意义吗?
最佳答案
Is
itertools.accumulate(my_list)
using an accurate sum function internally for floats likemath.fsum()
or not?
不,PyNumber_Add
用于 itertools source code 。 PyNumber_Add
是 standard addition, like x + y
在Python中
If possible, can
math.fsum
specified initertools.accumulate
as the addition function to be used?
是的,您可以使用 optional func
parameter 指定它:
import itertools
import math
l = [.1, .2, .3, .4, .5]
list(itertools.accumulate(l, lambda x, y: math.fsum([x, y])))
Does that make sense?
否,如 stated in the documentation , math.fsum
avoids loss of precision by tracking multiple intermediate partial sums
因此,仅对同时使用两个以上的 float 使用它才有意义:
>>> 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]
关于python - Python 3 中 float 的精确累积和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57425696/