给定一个概率密度函数,
我想通过生成从 0 到 1 的均匀分布数 p 并将它们插入分位数函数来生成按照上述概率密度函数分布的随机数。
按照以下方式在 R 编程中编码,
rand_pdf <- function(n) {
# generating uniformly distributed numbers p from 0 to 1
p <- runif(n)
# Calculate the corresponding quantiles using the inverse of the CDF (manually)
q <- ifelse(p <= 1/4, sqrt((p-1/4)/2) - 1/2, (7 - 3*sqrt(7*(1-p)))/2)
# Return the generated random numbers
return(q)
}
似乎效率不高,因为如果pdf被更改怎么办?有什么有效的方法可以不用手动计算就可以得到分位数吗?
n <- 10000
random_numbers <- rand_pdf(n)
# Create a histogram of the generated random numbers
hist(random_numbers, breaks = 100, freq = FALSE)
# Overlay the PDF on the histogram
curve(ifelse(x < -1/4 | x >= 7/4, 0,
ifelse(x < 0, 4*x+1, -4/7*x+1)),
from = -1, to = 2, add = TRUE, col = "darkblue")
直方图不是跟着PDF的曲线走吗?从输出看起来不是这样。