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.我怎么做随机值?
正如弗朗西斯所提到的,你最好知道你的发行版的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)
无需使用 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)
| 归档时间: |
|
| 查看次数: |
3233 次 |
| 最近记录: |