我正在使用 PyCharm Professional 和 Python 3.7.4 64 位。
当我评估结果时
np.arange(2, 4, 0.01)
它的显示精度错误(见图)。
np.array([x / 100 for x in range(200, 400)])
按预期显示,没有这些错误。
为什么会发生这些错误以及如何预防它们?
最佳答案
没有 pycharm 并发症:
In [284]: np.arange(2,2.1, 0.01)
Out[284]: array([2. , 2.01, 2.02, 2.03, 2.04, 2.05, 2.06, 2.07, 2.08, 2.09, 2.1 ])
In [285]: np.arange(2,2.1, 0.01).tolist()
Out[285]:
[2.0,
2.01,
2.0199999999999996,
2.0299999999999994,
2.039999999999999,
2.049999999999999,
2.0599999999999987,
2.0699999999999985,
2.0799999999999983,
2.089999999999998,
2.099999999999998]
float 从来都不是“精确的”。第三项是,'epsilon' 内等于 2.02。 Out[284]
显示四舍五入到一致大小的值,Out285]
是 Python 列表显示,显示每个元素的完整 float 荣耀。
np.arange
警告 float 步骤:
When using a non-integer step, such as 0.1, the results will often not
be consistent. It is better to use `numpy.linspace` for these cases.
linspace
更好地处理最终值,但仍然显示浮点显示限制:
In [287]: np.linspace(2,2.1,11)
Out[287]: array([2. , 2.01, 2.02, 2.03, 2.04, 2.05, 2.06, 2.07, 2.08, 2.09, 2.1 ])
In [288]: np.linspace(2,2.1,11).tolist()
Out[288]:
[2.0,
2.01,
2.02,
2.0300000000000002,
2.04,
2.05,
2.06,
2.0700000000000003,
2.08,
2.09,
2.1]
列表理解的另一种选择是缩放整数arange
In [291]: np.arange(200,210)/100
Out[291]: array([2. , 2.01, 2.02, 2.03, 2.04, 2.05, 2.06, 2.07, 2.08, 2.09])
关于python - 为什么 PyCharm 中 numpy 的范围显示精度错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59144974/