Create an array with a pre determined mean and standard deviation

荒凉一梦 提交于 2019-12-07 03:01:13

问题


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?


回答1:


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)



回答2:


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=10)
# array([ 0.03741785,  0.02154339,  0.04119221,  0.06307575,  0.01914617])



回答3:


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.



来源:https://stackoverflow.com/questions/50177594/create-an-array-with-a-pre-determined-mean-and-standard-deviation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!