0

I have such snippet of code:

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

Result:

[[ 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!

Gusev Slava
  • 2,136
  • 3
  • 21
  • 26

1 Answers1

1

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

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')
ewcz
  • 12,819
  • 1
  • 25
  • 47