用给定的概率密度函数生成随机数 [英] Generating random numbers with a given probability density function
问题描述
我想指定分布的概率密度函数,然后随机选取 N 个来自 Python 中该分布的数字.我该怎么做?
I want to specify the probability density function of a distribution and then pick up N random numbers from that distribution in Python. How do I go about doing that?
推荐答案
一般来说,你希望有逆累积概率密度函数.一旦你有了它,那么沿着分布生成随机数就很简单了:
In general, you want to have the inverse cumulative probability density function. Once you have that, then generating the random numbers along the distribution is simple:
import random
def sample(n):
return [ icdf(random.random()) for _ in range(n) ]
或者,如果您使用 NumPy:
Or, if you use NumPy:
import numpy as np
def sample(n):
return icdf(np.random.random(n))
在这两种情况下,icdf
都是逆累积分布函数,它接受 0 到 1 之间的值,并从分布中输出相应的值.
In both cases icdf
is the inverse cumulative distribution function which accepts a value between 0 and 1 and outputs the corresponding value from the distribution.
为了说明 icdf
的性质,我们将以值 10 和 12 之间的简单均匀分布为例:
To illustrate the nature of icdf
, we'll take a simple uniform distribution between values 10 and 12 as an example:
概率分布函数在 10 到 12 之间为 0.5,其他地方为零
probability distribution function is 0.5 between 10 and 12, zero elsewhere
累积分布函数是 0 低于 10(没有低于 10 的样本),高于 12(没有超过 12 的样本)并且在值之间线性增加(PDF 的积分)
cumulative distribution function is 0 below 10 (no samples below 10), 1 above 12 (no samples above 12) and increases linearly between the values (integral of the PDF)
逆累积分布函数仅定义在 0 和 1 之间.0 时为 10,12 时为 1,并且在值之间线性变化
inverse cumulative distribution function is only defined between 0 and 1. At 0 it is 10, at 12 it is 1, and changes linearly between the values
当然,难点在于获得逆累积密度函数.这真的取决于你的分布,有时你可能有一个分析函数,有时你可能想要求助于插值.数值方法可能很有用,因为数值积分可用于创建 CDF,插值可用于反演.
Of course, the difficult part is obtaining the inverse cumulative density function. It really depends on your distribution, sometimes you may have an analytical function, sometimes you may want to resort to interpolation. Numerical methods may be useful, as numerical integration can be used to create the CDF and interpolation can be used to invert it.
这篇关于用给定的概率密度函数生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!