w3resource

NumPy: Create a 5x5 array with random values and find the minimum and maximum values

NumPy: Random Exercise-4 with Solution

Write a NumPy program to create a 5x5 array with random values and find the minimum and maximum values.

Sample Solution :

Python Code :

# Importing the NumPy library as np

import numpy as np

# Generating a 5x5 NumPy array 'x' filled with random floats between 0 and 1 using np.random.random()

x = np.random.random((5, 5))

# Printing the original array 'x'
print("Original Array:")
print(x)

# Calculating the minimum and maximum values in array 'x' using x.min() and x.max() functions
xmin, xmax = x.min(), x.max()

# Printing the minimum and maximum values of the array 'x'
print("Minimum and Maximum Values:")
print(xmin, xmax) 

Sample Output:

Original Array:                                                        
[[ 0.3839264   0.6527485   0.41092465  0.63987331  0.72739435]         
 [ 0.1711146   0.7542493   0.30799339  0.79689356  0.92014308]         
 [ 0.14420449  0.28689129  0.69339598  0.26608753  0.20895817]         
 [ 0.20215693  0.36993965  0.21283682  0.33183608  0.92672618]         
 [ 0.25734144  0.01083637  0.41502065  0.90604563  0.92236538]]        
Minimum and Maximum Values:                                            
0.0108363710034 0.926726177113

Explanation:

In the above exercise –

x = np.random.random((5,5)): This code generates a 2-dimensional array (5x5) of random floating-point numbers using the np.random.random() function. The input tuple (5,5) specifies the shape of the array, which has 5 rows and 5 columns.

xmin, xmax = x.min(), x.max(): This code calculates the minimum and maximum values present in the x array using the min() and max() methods, respectively. These values are then assigned to the variables xmin and xmax.

print(xmin, xmax): This line prints the minimum and maximum values (xmin and xmax) found in the x array.

Pictorial Presentation:

NumPy Random: Create a 5x5 array with random values and find the minimum and maximum values

Python-Numpy Code Editor:

Previous: Write a NumPy program to create a 3x3x3 array with random values.
Next: Write a NumPy program to create a random 10x4 array and extract the first five rows of the array and store them into a variable.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.