Matlab 的evrnd 从 Gumbel 分布(也称为 I 型极值分布)生成随机变量。如该链接中所述,
这里使用的版本适合建模最小值;此分布的镜像可用于通过否定 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_l 的 rvs 方法。 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)