w3resource

NumPy: Compute the average, variance, standard deviation of an array of 1000 elements


Write a NumPy program to create a random array with 1000 elements and compute the average, variance, standard deviation of the array elements.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Generating an array of 1000 random samples from a standard normal distribution
x = np.random.randn(1000)

# Displaying the average of the array elements
print("Average of the array elements:")
mean = x.mean()  # Calculating the mean
print(mean)

# Displaying the standard deviation of the array elements
print("Standard deviation of the array elements:")
std = x.std()  # Calculating the standard deviation
print(std)

# Displaying the variance of the array elements
print("Variance of the array elements:")
var = x.var()  # Calculating the variance
print(var) 

Sample Output:

Average of the array elements:                                         
-0.0255137240796                                                       
Standard deviation of the array elements:                              
0.984398282476                                                         
Variance of the array elements:                                        
0.969039978542

Explanation:

In the above code –

x = np.random.randn(1000) –> This code generates an array of 1000 random numbers drawn from a standard normal distribution using np.random.randn().

mean = x.mean() –> The mean() function calculates the average value of the elements in the array. In this case, it calculates the mean of the 1000 random numbers.

std = x.std() –> The std() function calculates the standard deviation of the elements in the array. In this case, it calculates the standard deviation of the 1000 random numbers.

var = x.var() -> The var() calculates the variance of the elements in the array. It is equal to the square of the standard deviation. In this case, it calculates the variance of the 1000 random numbers.

Python-Numpy Code Editor: