【问题标题】:Why is numpy's arange displayed with precision errors in PyCharm?为什么 numpy 的范围在 PyCharm 中显示有精度错误?
【发布时间】:2020-03-27 10:09:35
【问题描述】:

我正在使用 PyCharm Professional 和 Python 3.7.4 64 位。

当我评估结果时

np.arange(2, 4, 0.01)

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

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

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

为什么会出现这些错误以及如何预防?

【问题讨论】:

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


    【解决方案1】:

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

    浮点数永远不是“精确的”。第三项是,在 'epsilon' 内等于 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.
    

    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])
    

    【讨论】:

    • 即使在我的两个初始语句中都添加了.tolist(),结果似乎也没有改变。 arange 仍然显示不准确,除以 100 的数组没有。这是显示错误还是后一组中的数字真的正确?
    【解决方案2】:

    这是由于在第 n 个精度点处的随机系统精度误差。如果我们将精度降低,它将是固定的。一种解决方法是使用 np.round 达到所需的精度。

    ex : np.round(np.linspace(2,2.1,11).tolist(),3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 2020-08-12
      相关资源
      最近更新 更多