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

标签 python python-3.x numpy pycharm numpy-ndarray

我正在使用 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

最佳答案

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

相关文章:

python - 为什么使用 pip 而不是 easy_install?

python - 通过固定间隔采样将列表缩小到固定大小

python - 如何在python函数中删除一个对象?

python - numpy 索引错误 : too many indices for array when indexing matrix with another

Python AWS BOTO 错误

python - 将 pandas DataFrame 与 NaN 合并以查找缺失行

python - 无法将干净的 unicode 文本插入 pandas 中的 DataFrame

python - 寻找最大的质因数(最快的程序)

python-3.x - 如何从 gensim 模块导入 WordEmbeddingSimilarityIndex 函数?

python - 将值(0 除外)从数组 2 复制到数组 1