w3resource

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

NumPy Mathematics: Exercise-20 with Solution

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:

Previous: Write a NumPy program to calculate mean across dimension, in a 2D numpy array.
Next: Write a NumPy program to compute the trigonometric sine, cosine and tangent array of angles given in degrees.

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://w3resource.com/python-exercises/numpy/python-numpy-math-exercise-20.php