numpy:浮点比较 [英] Numpy: Floating point comparison

查看:72
本文介绍了numpy:浮点比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码段:

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

为什么我们得到这样的结果?在第一行中,比较是正确的,但是在第二行和第三行中,结果对我来说是意外的.

Why we get such result? In the first row the comparison is correct but in second and in the third row the result is unexpected for me.

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

It's because of float comparison and floating point? With help of guys I understand the problem!

推荐答案

是的,因为像 3.1 这样的数字不能完全表示为浮点数.您甚至可以不使用numpy进行检查:

yes, it's because numbers like 3.1 etc. are not exactly representable as floating point numbers. You can check it even without using numpy:

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

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

one can inspect the internals in more detail using the decimal module:

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

这篇关于numpy:浮点比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆