简体   繁体   English

创建一个具有预先确定的平均值和标准偏差的数组

[英]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.我正在尝试使用 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 .使用numpy.random.normal If your mean is my_mean and your std my_str :如果你的意思是my_mean和你的 std my_str

x = np.random.normal(loc=my_mean, scale=my_std, size=1000)

Another solution, using np.random.randn :另一个解决方案,使用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 :使用相同的随机种子,这实际上产生与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.最后两个必须通过求解由 mean 和 stddev 公式给出的方程组来计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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