w3resource

NumPy: Check two random arrays are equal or not

NumPy: Random Exercise-10 with Solution

Write a NumPy program to check two random arrays are equal or not.

Sample Solution:

Python Code :

# Importing the NumPy library as np
import numpy as np

# Generating the first array 'x' with 6 random integers (0 or 1) using np.random.randint()
x = np.random.randint(0, 2, 6)

# Printing the first generated array 'x'
print("First array:")
print(x)

# Generating the second array 'y' with 6 random integers (0 or 1) using np.random.randint()
y = np.random.randint(0, 2, 6)

# Printing the second generated array 'y'
print("Second array:")
print(y)

# Checking if the two arrays 'x' and 'y' are equal using np.allclose()
# This function returns True if the two arrays are element-wise equal within a tolerance
array_equal = np.allclose(x, y)

# Printing whether the two arrays are equal or not
print("Test above two arrays are equal or not!")
print(array_equal) 

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:

NumPy Random: Check two random arrays are equal or not.

Python-Numpy Code Editor:

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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-random-exercise-10.php