NumPy: Check two random arrays are equal or not
10. Check Array Equality
Write a NumPy program to check two random arrays are equal or not.
Sample Solution:
Python Code :
Sample Output:
First array: [1 0 0 0 1 0] Second array: [0 0 1 1 0 1] Test above two arrays are equal or not! False
Explanation:
In the above exercise –
x = np.random.randint(0, 2, 6): This line creates a 1D array x with 6 random integers between 0 and 1 using the np.random.randint() function. The input values 0 and 2 specify the lower (inclusive) and upper (exclusive) boundaries for the random integers, and 6 is the size of the output array.
y = np.random.randint(0, 2, 6): This line creates another 1D array y with the same specifications as x.
array_equal = np.allclose(x, y): This line checks if the two arrays x and y are element-wise equal using the np.allclose() function. The function returns True if all elements in the arrays are approximately equal within a specified tolerance, and False otherwise. In this case, since we're comparing integers, the default tolerance is effectively zero, meaning that the function checks for exact equality.
Pictorial Presentation:
For more Practice: Solve these Related Problems:
- Write a function that compares two arrays element-wise and returns True if all elements match exactly.
- Implement a solution that checks array equality using np.array_equal and np.allclose for floating-point arrays.
- Create a program that reports the indices where two arrays differ if they are not equal.
- Test the equality function on arrays with different shapes and dtypes to ensure robust error handling.
Go to:
Previous: Write a NumPy program to find the nearest value from a given value in an array.
Next: Write a NumPy program to create random vector of size 15 and replace the maximum value by -1.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.