我有这样的概率密度函数:
def p1(x):
return ( sin(x) ** (-0.75) ) / (4.32141 * (x ** (1/5)))我想用这个[0; 1]来去除pdf上的随机值。我怎么做随机值?
发布于 2015-03-17 09:59:47
正如方济各提到的,你最好知道你的分布情况。总之,way为定义自定义发行版提供了一种方便的方法。看上去就像那样
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()发布于 2017-03-01 15:16:07
不使用can并给出PDF的数值抽样,您可以使用累积分布和线性插值进行抽样。下面的代码在x中假设相同的间距。它可以被修改为对任意采样的PDF进行集成。注意,它在x的范围内将PDF重命名为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 randdisthttps://stackoverflow.com/questions/29095070
复制相似问题