python - Python 3 中 float 的精确累积和

标签 python python-3.x math floating-point python-itertools

给定 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 like math.fsum() or not?

不,PyNumber_Add 用于 itertools source codePyNumber_Addstandard addition, like x + y在Python中

If possible, can math.fsum specified in itertools.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/

相关文章:

math - 不想在绘图轴上使用科学记数法

python - 如何从另一个脚本将 Bottle 作为守护进程启动?

python - 在不使用集合的情况下,在嵌套的 for 循环中对 dict 和 list 中的项目进行成员资格检查?

python-3.x - 如何更快地从视频中提取帧?

python - pprint 十六进制数

python - 在 Python 中实现 SVG 圆弧曲线

java - 如何在java方法中进行数学运算?

python - 将多个 isinstance 检查转换为结构模式匹配

python - 不应自动运行的 Django 测试

python - NAME 公式中的间接引用过多