我想快速生成离散随机数,其中我有一个已知的 CDF。本质上,算法是:
cdf
u
u < cdf[1]
选择 1 u < cdf[2]
选择 2 u < cdf[3]
选择 3*...
示例
首先生成一个cdf:
cdf = cumsum(runif(10000, 0, 0.1))
cdf = cdf/max(cdf)
接下来生成
N
统一随机数:N = 1000
u = runif(N)
现在对值进行采样:
##With some experimenting this seemed to be very quick
##However, with N = 100000 we run out of memory
##N = 10^6 would be a reasonable maximum to cope with
colSums(sapply(u, ">", cdf))
最佳答案
如何使用 cut
:
N <- 1e6
u <- runif(N)
system.time(as.numeric(cut(u,cdf)))
user system elapsed
1.03 0.03 1.07
head(table(as.numeric(cut(u,cdf))))
1 2 3 4 5 6
51 95 165 172 148 75
关于r - 高效生成离散随机数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15137459/