简体   繁体   中英

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?

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)

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])

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM