如何绘制函数的概率密度函数?

时间:2010-08-25 04:13:23

标签: r

假设A遵循指数分布; B遵循Gamma分布 如何绘制0.5 *(A + B)的PDF

4 个答案:

答案 0 :(得分:9)

使用“distr”包非常简单:

library(distr)

A <- Exp(rate=3)
B <- Gammad(shape=2, scale=3)

conv <- 0.5*(A+B)

plot(conv)
plot(conv, to.draw.arg=1)

由JD Long编辑

结果情节如下: alt text

答案 1 :(得分:7)

如果您只是在寻找快速图表,我通常会采用快速而肮脏的模拟方法。我做了一些绘画,在绘画上猛击高斯密度并绘制那个坏男孩:

numDraws   <- 1e6
gammaDraws <- rgamma(numDraws, 2)
expDraws   <- rexp(numDraws)
combined   <- .5 * (gammaDraws + expDraws)
plot(density(combined))

输出应该看起来像这样:

alt text

答案 2 :(得分:2)

这是尝试在R中进行卷积(@Jim Lewis所指的)。注意,可能有更有效的方法来做到这一点。

lower <- 0
upper <- 20
t <- seq(lower,upper,0.01)
fA <- dexp(t, rate = 0.4)
fB <- dgamma(t,shape = 8, rate = 2)
## C has the same distribution as (A + B)/2
dC <- function(x, lower, upper, exp.rate, gamma.rate, gamma.shape){
  integrand <- function(Y, X, exp.rate, gamma.rate, gamma.shape){
    dexp(Y, rate = exp.rate)*dgamma(2*X-Y, rate = gamma.rate, shape = gamma.shape)*2
  }
  out <- NULL
  for(ix in seq_along(x)){
    out[ix] <-
      integrate(integrand, lower = lower, upper = upper,
                X = x[ix], exp.rate = exp.rate,
                gamma.rate = gamma.rate, gamma.shape = gamma.shape)$value
  }
  return(out)
}
fC <- dC(t, lower=lower, upper=upper, exp.rate=0.4, gamma.rate=2, gamma.shape=8)
## plot the resulting distribution
plot(t,fA,
     ylim = range(fA,fB,na.rm=TRUE,finite = TRUE),
     xlab = 'x',ylab = 'f(x)',type = 'l')
lines(t,fB,lty = 2)
lines(t,fC,lty = 3)
legend('topright', c('A ~ exp(0.4)','B ~ gamma(8,2)', 'C ~ (A+B)/2'),lty = 1:3)

答案 3 :(得分:1)

我不是R程序员,但知道对于具有PDF的独立随机变量f 1 (x)和f 2 (x)可能会有所帮助,PDF 这两个变量之和由两个输入PDF的卷积f 1 * f 2 (x)给出。

相关问题