首页 > 解决方案 > 创建 Numpy 数组时如何避免精度错误?

问题描述

我必须在我的代码中获得一定的精度。但是,我认为由于对长数组中的错误进行汇总,它会累积更大的错误。你能找出为什么元素 38260 不等于 5.6 吗?

import numpy as np

xmin = -377
xmax = 345
spacing = 0.01

a = np.arange(xmin,xmax,spacing)
print('{0:.25f}'.format(a[38260]))
# Prints 5.5999999996520273271016777
print(a[38260] == 5.6)
# Prints false

b = np.arange(xmin/spacing,xmax/spacing)*spacing
print('{0:.25f}'.format(b[38260]))
#Prints 5.6000000000000005329070518
print(b[38260] == 5.6)
#Prints false

标签: pythonnumpyprecision

解决方案


您可以通过创建一个np.int32开头来避免错误累积,然后将其划分为您的浮点值范围:

import numpy as np

xmin = -37700  # times 100
xmax = 34500   # times 100
spacing = 1    # times 100

b = np.arange(xmin, xmax, spacing)  # np.int32 array - no loss of precision

a = b / 100.0  # divide by 100      # np.float64 array - closer to what you want

print('{0:.25f}'.format(a[38260]))
print(a[38260] == 5.6)

输出:

 5.6
 True

仍然建议使用np.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)而不是==进行相等比较。

你的原始代码已经np.float64在我的系统上使用了,所以我看不出有什么办法让它更精确,而且众所周知,浮点数很难使用,请参阅:


推荐阅读