为什么numpy的范围显示为PyCharm中的精度错误?

问题描述 投票:1回答:1

我正在将PyCharm Professional与Python 3.7.4 64位一起使用。

[当我评估结果时

np.arange(2, 4, 0.01)

它以精确的错误显示(见图)。

np.array([x / 100 for x in range(200, 400)])

按预期显示,没有这些错误。

为什么会发生这些错误以及如何防止它们?

enter image description here

python python-3.x numpy pycharm numpy-ndarray
1个回答
0
投票

没有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]

浮点永远不会是“精确的”。第三项是在“ε”内等于2.02。 Out[284]显示的值四舍五入到一个一致的大小,Out285]是Python列表显示,显示每个元素的完整浮动值。

[np.arange警告关于浮动步长:

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.
© www.soinside.com 2019 - 2024. All rights reserved.