I am new to Python. I cannot understand the behavior of the following code (I am trying to create a unit test for something):
import numpy as np
input = np.array([0, 2])
result = 1 / (1 + np.exp(-input))
expected_result = np.array([0.5, 0.88079708])
print(result)
print(expected_result)
print(result[1])
print(expected_result[1])
is_equal1 = np.array_equal(result, expected_result)
is_equal2 = np.allclose(result, expected_result, rtol=0.00000000000000000000001)
print(is_equal1)
print(is_equal2)
This code prints:
[0.5 0.88079708] [0.5 0.88079708] 0.8807970779778823 0.88079708 False True
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.