python - 创建 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
解决方案
您可以通过创建一个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
在我的系统上使用了,所以我看不出有什么办法让它更精确,而且众所周知,浮点数很难使用,请参阅:
推荐阅读
- android - 如何使用 Flutter 处理应用程序生命周期(在 Android 和 iOS 上)?
- nsis - 如何在 Nsis 中创建 zip 文件
- git - Github 比较来自不同用户的两个不同存储库
- node.js - 未安装的节点,仍然“node -v”打印节点的版本。如何修复它(如何完全删除节点)?
- c# - 如何从 javascript 调用 C# 类的 void 方法 - ASP .Net MVC C#
- materialize - Materialise 芯片 - 区分大小写的芯片
- google-tag-manager - 谷歌标签管理器发布不起作用
- compiler-errors - 没有root的caffe:/usr/bin/ld:找不到-lxxxx
- spring - Spring自定义登录页面始终将用户标记为匿名
- android - 无法检查用户是否登录