使用numpy.randn(),numpu.random.normal和numpu.random.standard_normal()函数创建一维高斯分布

查阅numpy文档我们可以看到,numpy.randn(),numpu.random.normalnumpu.random.standard_normal()函数均可用来得到指定个数的高斯分布返回值。前几天我突发奇想,有没有办法来用他们产生一维高斯分布呢?答案是可以的。

class GaussianDistribution:
    @staticmethod
    def selfMadeMethod():
        num = 1001
        array = np.random.randn(num)
        max_ = np.max(abs(array))
        x = np.linspace(-max_, max_, num)
        result = np.ones(num - 1)
        for i in range(num):
            for j in range(num - 1):
                if x[j] < array[i] < x[j + 1]:
                    result[j] += 1
        real_x = np.linspace(-max_ + max_ * 2 / (num - 1), max_ - max_ * 2 / (num - 1), num - 1)
        plt.figure(1)
        plt.title('1D Gaussian Distribution')
        plt.plot(real_x, result)

    @staticmethod
    def numpyRandomRandn():
        num = 1001
        array = np.random.randn(num)
        plt.figure(2)
        plt.title('1D Gaussian Distribution')
        plt.hist(array, 50, density=True)

    @staticmethod
    def numpyRandomNormal():
        mu, sigma = 0, 0.1  # mean and standard deviation
        s = np.random.normal(mu, sigma, 1000)
        plt.figure(3)
        plt.title('1D Gaussian Distribution')
        plt.hist(s, 50, density=True)

    @staticmethod
    def numpyRandomStandardNormal():
        s = np.random.standard_normal(1000)
        plt.figure(4)
        plt.title('1D Gaussian Distribution')
        plt.hist(s, 50, density=True)
        plt.show()


if __name__ == '__main__':
    gaussian = GaussianDistribution()
    gaussian.selfMadeMethod()
    gaussian.numpyRandomRandn()
    gaussian.numpyRandomNormal()
    gaussian.numpyRandomStandardNormal()

selfMadeMethod()函数中的方法在某种程度上等同于另外三种方法,四种方法的结果如下图所示。

selfMadeMethod()方法结果:
gaussian distribution
我们可以看到,这里的图像大概为一个高斯分布型,当然与理想中光滑的曲线有一定的差异,毕竟我们是随机产生高斯分布的数值,推测当随即点数足够多的时候,曲线会逐渐趋于光滑状态。然而说明问题就好了,如何优化这里不做过多讨论。
numpyRandomRandn()方法结果:
gaussian distribution
numpyRandomNormal()方法结果:
gaussian distribution

numpyRandomStandardNormal()方法结果:
gaussian distribution
我们可以看到,结果上都近似为高斯分布,且三幅hist图像中面积的总积分为1。然而实际上还是有些许差异。但是使用三个随机函数来产生高斯分布的结果是可能的。

码字不易,如果大家觉得有用,请高抬贵手给一个赞让我上推荐让更多的人看到吧~

猜你喜欢

转载自blog.csdn.net/u011699626/article/details/112062173
今日推荐