9

我想在python中使用高斯函数在给出平均值和方差的特定范围之间生成一些数字

所以可以说我的范围在 0 到 10 之间

我希望我的平均值为 3,方差为 4

均值 = 3,方差 = 4

我怎样才能做到这一点 ?

4

6 回答 6

19

使用random.gauss. 从文档

random.gauss(mu, sigma)
    Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly
    faster than the normalvariate() function defined below.

在我看来,你可以钳制这个结果,但这不会使它成为高斯分布。我认为您不能同时满足所有约束。如果你想把它限制在 range [0, 10],你可以得到你的数字:

num = min(10, max(0, random.gauss(3, 4)))

但是,由此产生的数字分布将不是真正的高斯分布。在这种情况下,您似乎也不能吃蛋糕。

于 2013-05-09T21:54:24.470 回答
6

可能有更好的方法来做到这一点,但这是我最终为解决这个问题而创建的函数:

import random

def trunc_gauss(mu, sigma, bottom, top):
    a = random.gauss(mu,sigma))
    while (bottom <= a <= top) == False:
        a = random.gauss(mu,sigma))
    return a

如果我们逐行分解:

import random

这允许我们使用随机库中的函数,其中包括一个高斯随机数生成器(random.gauss)。

def trunc_gauss(mu, sigma, bottom, top):

函数参数允许我们指定均值 (mu) 和方差 (sigma),以及所需范围的顶部和底部。

a = random.gauss(mu,sigma))

在函数内部,我们根据高斯分布生成一个初始随机数。

while (bottom <= a <= top) == False:
a = random.gauss(mu,sigma))

接下来,while 循环检查数字是否在我们指定的范围内,只要当前数字在我们的范围之外,就会生成一个新的随机数。

return a

一旦数字在我们的范围内,while 循环就会停止运行并且函数返回数字。

这应该可以更好地近似高斯分布,因为我们不会通过向上或向下舍入异常值来人为地扩大范围的顶部和底部边界。

我对 Python 很陌生,所以很可能有更简单的方法,但这对我有用。

于 2014-11-14T00:06:43.707 回答
3

我正在做一些数值分析计算,我遇到了这个 python 教程网站 - http://www.python-course.eu/weighted_choice_and_sample.php

现在,如果有人太忙而无法访问该站点,这就是我提供的解决方案。我不知道你需要多少个高斯值,所以我将使用 100 作为 n,你给出的 mu 作为 3,方差作为 4,这使得 sigma = 2。这是代码:

from random import gauss
n = 100
values = []
frequencies = {}
while len(values) < n:
    value = gauss(3, 2)
    if 0 < value < 10:
        frequencies[int(value)] = frequencies.get(int(value), 0) + 1
        values.append(value)
print(values)

我希望这有帮助。你也可以得到情节。这一切都在教程中。

于 2017-08-16T08:51:30.377 回答
1

如果您的整数范围很小,您可以创建一个列表,该列表具有该范围内数字的高斯分布,然后从中进行随机选择。

于 2013-05-09T22:11:23.920 回答
0
import numpy as np 
from random import uniform
from scipy.special import erf,erfinv
import math 

def trunc_gauss(mu, sigma,xmin=np.nan,xmax=np.nan):
    """Truncated Gaussian distribution.

    mu is the mean, and sigma is the standard deviation.  

    """

    if np.isnan(xmin):
        zmin=0
    else:
        zmin = erf((xmin-mu)/sigma)
    if np.isnan(xmax):
        zmax=1
    else:
        zmax = erf((xmax-mu)/sigma)

    y = uniform(zmin,zmax)
    z = erfinv(y)
    
    # This will not come up often but if y >= 0.9999999999999999      
    # due to the truncation of the ervinv function max z = 5.805018683193454

    while math.isinf(z):
        z = erfinv(uniform(zmin,zmax))
    return mu + z*sigma
于 2020-10-30T17:22:13.117 回答
0

您可以对 150 个变量使用简约代码:

import numpy as np
s = np.random.normal(3,4,150)             #<= mean = 3, variance = 4
print(s)

正态分布是另一种类似于随机的随机分布。所以,我们可以通过以下方式检查:

import seaborn as sns
import matplotlib.pyplot as plt

AA1_plot  = sns.distplot(s, kde=True, rug=False)
plt.show()
于 2019-01-10T17:43:10.143 回答