首页 > 解决方案 > 相当于 Python 中的 evrnd(mu,sigma,m,n)

问题描述

我想要在Python中替代这个Matlab 函数

evrnd(mu,sigma,m,n)

我想我们可以使用这样的东西

numpy.random.gumbel

要不就

numpy.random.uniform

提前致谢。

标签: pythonmatlabnumpyrandomdistribution

解决方案


Matlabevrnd从 Gumbel 分布(也称为 I 型极值分布)生成随机变量。如该链接中所述,

这里使用的版本适用于建模最小值;此分布的镜像可用于通过否定 R 来模拟最大值。

您可以使用NumPy 的 Gumbel 分布实现,但它使用模拟最大值的分布版本,因此您必须围绕位置(即 mu)参数翻转值。

这是一个包含 Python 函数的脚本evrnd。它生成的图如下。

import numpy as np


def evrnd(mu, sigma, size=None, rng=None):
    """
    Generate random variates from the Gumbel distribution.

    This function draws from the same distribution as the Matlab function

        evrnd(mu, sigma, n)

    `size` may be a tuple, e.g.

    >>> evrnd(mu=3.5, sigma=0.2, size=(2, 5))
    array([[3.1851337 , 3.68844487, 3.0418185 , 3.49705362, 3.57224276],
           [3.32677795, 3.45116032, 3.22391284, 3.25287589, 3.32041355]])

    """
    if rng is None:
        rng = np.random.default_rng()
    x = mu - rng.gumbel(loc=0, scale=sigma, size=size)
    return x


if __name__ == '__main__':
    import matplotlib.pyplot as plt

    mu = 10
    sigma = 2.5
    n = 20000

    x = evrnd(mu, sigma, n)

    # Plot the normalized histogram of the sample.
    plt.hist(x, bins=100, density=True, alpha=0.7)
    plt.grid(alpha=0.25)
    plt.show()

阴谋


如果您已经在使用 SciPy,另一种方法是rvs使用scipy.stats.gumbel_l. SciPy 分布scipy.stats.gumbel_l实现了 Gumbel 分布的最小值,因此不需要翻转rvs方法返回的结果。例如,

from scipy.stats import gumbel_l                                      


mu = 10
sigma = 2.5
n = 20000

x = gumbel_l.rvs(loc=mu, scale=sigma, size=n)


推荐阅读