【问题标题】:Numpy: Floating point comparison [duplicate]Numpy:浮点比较[重复]
【发布时间】:2023-04-05 21:12:02
【问题描述】:

我有这样的sn-p代码:

eps = 0.1
xx = np.array([[1,2,3], [4,5,6], [7,8,9]])
yy = np.array([[1.1,2.1,3.1], [4.1,5.1,6.1], [7.1,8.1,9.2]])
dif = np.absolute(xx - yy)
print dif
print dif < eps

结果:

[[ 0.1  0.1  0.1]
[ 0.1  0.1  0.1]
[ 0.1  0.1  0.2]]

[[False False False]
[ True  True  True]
[ True  True False]]

为什么我们会得到这样的结果?在第一行,比较是正确的,但在第二行和第三行,结果出乎我的意料。

是因为浮点比较和浮点? 在伙计们的帮助下,我明白了这个问题!

【问题讨论】:

    标签: python numpy floating-point


    【解决方案1】:

    是的,这是因为像 3.1 等数字不能完全表示为浮点数。即使不使用 numpy 也可以检查:

    >>> 3.1 - 3 < 0.1
    False
    >>> 4.1 - 4 < 0.1
    True
    

    可以使用decimal 模块更详细地检查内部结构:

    >>> from decimal import Decimal
    >>> Decimal(0.1)
    Decimal('0.1000000000000000055511151231257827021181583404541015625')
    >>> Decimal(3.1)
    Decimal('3.100000000000000088817841970012523233890533447265625')
    >>> Decimal(4.1)
    Decimal('4.0999999999999996447286321199499070644378662109375')
    

    【讨论】:

      猜你喜欢
      • 2011-10-24
      • 2012-10-26
      • 1970-01-01
      • 2013-02-01
      • 2012-07-17
      • 2013-07-02
      • 2015-09-06
      相关资源
      最近更新 更多