首页 > 解决方案 > Numpy float16:不同索引顺序的不同求和结果

问题描述

当我运行这些简单的总和时,我得到了一些有趣的错误:

import numpy as np

data_type = np.float16
x = np.ones(shape=(3, 1000,10), dtype=data_type)
y = np.ones(shape=(3, 10000, 10), dtype=data_type)
z = np.ones(shape=(3, 11053, 10), dtype=data_type)

print("\nx: Both results are correct")
print(f"x[0,:,0].sum(0)={x[0,:,0].sum(0)}")
print(f"x[0].sum(0)[0]={x[0].sum(0)[0]}")

print("\ny: One result is correct, one is wrong")
print(f"y[0,:,0].sum(0)={y[0, :, 0].sum(0)}")
print(f"y[0].sum(0)[0]={y[0].sum(0)[0]}")

print("\nz: Both results are wrong")
print(f"z[0,:,0].sum(0)={z[0, :, 0].sum(0)}")
print(f"z[0].sum(0)[0]={z[0].sum(0)[0]}")

输出:

> x: Both results are correct
> x[0,:,0].sum(0)=1000.0
> x[0].sum(0)[0]=1000.0

> y: One result is correct, one is wrong
> y[0,:,0].sum(0)=10000.0
> y[0].sum(0)[0]=2048.0

> z: Both results are wrong
> z[0,:,0].sum(0)=11056.0
> z[0].sum(0)[0]=2048.0

使用 np.float32 或 np.float64 时不会发生错误。但是,根据np.finfo(np.float16).maxand np.finfo(np.float16).min, np.float16 的最大值和最小值是 +/- 65,500,因此它似乎不是由于溢出造成的。此外,在我的第二个示例中(使用y),一个总和结果是正确的,而另一个则不是,这似乎表明索引顺序有所不同。

知道发生了什么吗?

标签: pythonnumpyprecision

解决方案


推荐阅读