Skip to content
Advertisement

comparing numpy arrays with np.allclose()

I am new to Python. I cannot understand the behavior of the following code (I am trying to create a unit test for something):

JavaScript

This code prints:

JavaScript

Why when I print arrays their values are equal, but then I print their last items they are different? If the values are actually different, why is_equal2 is True? If the values are the same, why is_equal1 is False?

Advertisement

Answer

“Why when I print arrays their values are equal, but then I print their last items they are different?”

It is because numpy.ndarray has a preset display precision in print.

“If the values are actually different, why is_equal2 is True?”

According to the docs of numpy.allclose, it is comparing element-wise:

absolute(a – b) <= (atol + rtol * absolute(b))

atol is default to be 1e-8, so you need to provide atol parameter here instead of rtol.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement