首页 > 解决方案 > Python 3 中浮点数的准确累积和

问题描述

给定 Python 中的浮点数列表,生成该列表的累积和的最准确方法是什么?

我所说的准确是指对舍入误差具有鲁棒性。

特别是我想了解我是否应该使用list(itertools.accumulate(my_list))或计算这个列表成对使用math.fsum()

Numpy 不是一个选择。

是否itertools.accumulate(my_list)在内部对浮点数使用准确的求和函数math.fsum()

在这种情况下他们有什么区别?

如果可能的话,可以math.fsum指定为加法函数,itertools.accumulate这有意义吗?

标签: pythonpython-3.xmathfloating-pointitertools

解决方案


是否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]

推荐阅读