2

From my understanding of numpy, the np.equal([x, prod]) command compares the arrays element by element and returns True for each if they are equal. But every time I execute the command, it returns False for the first comparison. On the other hand, if I copy-paste the two arrays into the command, it returns True for both, as you can see in the screenshot. So, why is there a difference between the two?

enter image description here

9
  • 1
    When you compare them by hardcoded values, they will be equal as they are approximated in the exact same way. But once you apply some mathematical operation on them, it's no longer possible to check if two floating-points are equal. Commented Mar 12, 2020 at 17:28
  • 1
    Quick example: onlinegdb.com/B1SO-l_H8 Commented Mar 12, 2020 at 17:29
  • 1
    You could do that, or you compare them against a small delta. The reason you get a floating-point is that most mathematical operations require floating-point values, like the square root, dot product, matrix inverse and more. Commented Mar 12, 2020 at 17:31
  • 1
    By using a small delta, I mean comparing that two values are equal or just a really small value apart. Check this out: docs.scipy.org/doc/numpy/reference/generated/numpy.isclose.html Commented Mar 12, 2020 at 17:32
  • 1
    Or np.allclose if you do not need to return the mask. Commented Mar 12, 2020 at 17:33

1 Answer 1

2

You cannot compare floating-point numbers, as they are only an approximation. When you compare them by hardcoded values, they will be equal as they are approximated in the exact same way. But once you apply some mathematical operation on them, it's no longer possible to check if two floating-points are equal.

For example, this

a = 0

for i in range(10):
    a += 1/10
    
print(a)
print(a == 1)

will give you 0.9999999999 and False, even though (1/10) * 10 = 1.

To compare floating-point values, you need to compare the two values against a small delta value. In other words, check if they're just a really small value apart. For example

a = 0

for i in range(10):
    a += 1/10
    
delta = 0.00000001
print(a)
print(abs(a - 1) < delta)

will give you True.

For numpy, you can use numpy.isclose to get a mask or numpy.allclose if you only want a True or False value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.