如何从(任意)连续概率分布模拟?

Den*_*nis 5 python random distribution scipy python-3.x

我有一个像这样的概率密度函数:

def p1(x):
    return ( sin(x) ** (-0.75) ) / (4.32141 * (x ** (1/5)))
Run Code Online (Sandbox Code Playgroud)

我想[0; 1]用这个去除随机值pdf.我怎么做随机值?

Gio*_*elm 7

正如弗朗西斯所提到的,你最好知道你的发行版的cdf.无论如何,scipy提供了一种定义自定义分布的便捷方法.它看起来非常像那样

from scipy import stats
class your_distribution(stats.rv_continuous):
    def _pdf(self, x):
        return ( sin(x) ** (-0.75) ) / (4.32141 * (x ** (1/5)))

distribution = your_distribution()
distribution.rvs()
Run Code Online (Sandbox Code Playgroud)

  • (+1),很好的答案.如果事实证明它太慢了(因为它通过了通用代码路径),那么只有这样才能集成/插入cdf,并且它是随机采样的逆. (2认同)

xio*_*xox 5

无需使用 scipy 并给定 PDF 的数值采样,您可以使用累积分布和线性插值进行采样。下面的代码假设 x 中的间距相等。可以对其进行修改以对任意采样的 PDF 进行集成。请注意,它将 PDF 在 x 范围内重新归一化为 1。

import numpy as np

def randdist(x, pdf, nvals):
    """Produce nvals random samples from pdf(x), assuming constant spacing in x."""

    # get cumulative distribution from 0 to 1
    cumpdf = np.cumsum(pdf)
    cumpdf *= 1/cumpdf[-1]

    # input random values
    randv = np.random.uniform(size=nvals)

    # find where random values would go
    idx1 = np.searchsorted(cumpdf, randv)
    # get previous value, avoiding division by zero below
    idx0 = np.where(idx1==0, 0, idx1-1)
    idx1[idx0==0] = 1

    # do linear interpolation in x
    frac1 = (randv - cumpdf[idx0]) / (cumpdf[idx1] - cumpdf[idx0])
    randdist = x[idx0]*(1-frac1) + x[idx1]*frac1

    return randdist
Run Code Online (Sandbox Code Playgroud)