相当于 Python 中的 evrnd(mu,sigma,m,n)

equivalent to evrnd(mu,sigma,m,n) in Python

我想要在 Python

中替代此 Matlab 函数

evrnd(mu,sigma,m,n)

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

numpy.random.gumbel

numpy.random.uniform

提前致谢。

Matlab 的 evrnd 从 Gumbel 分布(也称为 I 型极值分布)生成随机变量。如 link、

中所述

The version used here is suitable for modeling minima; the mirror image of this distribution can be used to model maxima by negating R.

您可以使用 NumPy's implementation of the Gumbel distribution,但它使用模拟最大值的分布版本,因此您必须翻转位置(即 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,另一种方法是使用 scipy.stats.gumbel_lrvs 方法。 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)