Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array with a pre determined mean and standard deviation

I am attempting to create an array with a predetermined mean and standard deviation value using Numpy. The array needs random numbers within it.

So far I can produce an array and calculate the mean and std. but can not get the array to be controlled by the values:

import numpy as np
x = np.random.randn(1000)
print("Average:")
mean = x.mean()
print(mean)
print("Standard deviation:")
std = x.std()
print(std)

How to control the array values through the mean and std?

like image 742
EORS Avatar asked May 04 '18 14:05

EORS


3 Answers

Use numpy.random.normal. If your mean is my_mean and your std my_str:

x = np.random.normal(loc=my_mean, scale=my_std, size=1000)
like image 155
Jundiaius Avatar answered Nov 15 '22 14:11

Jundiaius


Another solution, using np.random.randn:

my_std * np.random.randn(1000) + my_mean

Example:

my_std = 0.025
my_mean = 0.025

x = my_std * np.random.randn(1000) + my_mean
x.mean()
# 0.025493112966038879
x.std()
# 0.024464870590114995

With the same random seed, this actually produces the exact same results as numpy.random.normal:

np.random.seed(42)
my_std * np.random.randn(5) + my_mean
# array([ 0.03741785,  0.02154339,  0.04119221,  0.06307575,  0.01914617])

np.random.seed(42)
np.random.normal(loc=my_mean, scale=my_std, size=5) #note the size here is 5 now
# array([ 0.03741785,  0.02154339,  0.04119221,  0.06307575,  0.01914617])
like image 26
sacuL Avatar answered Nov 15 '22 15:11

sacuL


Since you already know the mean and standard deviation, you have two degrees of freedom. This means that you can select random numbers for all but two elements of your array. The last two must be calculated by solving the system of equations given by the formulas for mean and stddev.

like image 1
Code-Apprentice Avatar answered Nov 15 '22 15:11

Code-Apprentice