python - 为什么 np.add.at() 对于大型数组返回错误的答案?

标签 python numpy

我有一个大型数据集,statistic,其中 statistic.shape = (1E10,),我想有效地将​​其(总和)合并到一个零数组中, out = np.zeros(1E10)statistic 中的每个条目都有一个相应的索引 idx,它告诉我它属于哪个 out bin。索引不是唯一的,因此我无法使用 out += statistic[idx] 因为这只会在第一次遇到特定索引时进行计数。因此我使用np.add.at(out, idx, statistic)。我的问题是,对于非常大的数组,np.add.at() 返回错误的答案。

下面是显示此行为的示例脚本。函数 check_add() 应返回 1。

import numpy as np

def check_add(N):
    N = int(N)
    out = np.zeros(N)
    np.add.at(out, np.arange(N), np.ones(N))
    return np.sum(out)/N

n_arr = [1E3, 1E5, 1E8, 1E10]
for n in n_arr:
    print('N = {} (log(N) = {}); output ratio is {}'.format(n, np.log10(n), check_add(n)))

这个例子返回给我:

N = 1000.0 (log(N) = 3.0); output ratio is 1.0
N = 100000.0 (log(N) = 5.0); output ratio is 1.0
N = 100000000.0 (log(N) = 8.0); output ratio is 1.0
N = 10000000000.0 (log(N) = 10.0); output ratio is 0.1410065408

有人可以向我解释一下为什么 N=1E10 的函数会失败吗?

最佳答案

这是一个老错误,NumPy issue 13286ufunc.at 使用的循环计数器变量太小。它得到了fixed不久前,所以更新你的 NumPy。 (此修复程序存在于 1.16.3 及更高版本中。)

关于python - 为什么 np.add.at() 对于大型数组返回错误的答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64803546/

相关文章:

python - Plotly:如何在组合图表中注释图形对象条形图?

python - 导入模块时将记录器对象作为参数

python - 手动设置图例中点的颜色

python - 如何使用 numpy(和 scipy)查找函数的所有零点?

Python:在放置请求中合并文件路径

python - 在 python 中抓取绝对 URL 而不是相对路径

python - SQLAlchemy db.create_all() 错误,未创建数据库

python - 将日期从 HDF5 数据集转换为 numpy 数组

python - 存储在 HDFStore 后取回 nan 值

python - 使用 numpy 从边缘列表中累积 "neigborhood"的值