首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何绘制函数的概率密度函数?

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

Stack Overflow用户
提问于 2010-08-25 12:13:23
回答 3查看 4.2K关注 0票数 7

假设A服从指数分布,B服从伽玛分布,如何绘制0.5*的PDF (A+B)

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-08-26 01:04:18

使用"distr“包可以非常简单地实现:

代码语言:javascript
复制
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编辑

生成的图如下所示:

票数 9
EN

Stack Overflow用户

发布于 2010-08-25 22:32:46

如果你只是在寻找快速的图形,我通常会使用快速而肮脏的模拟方法。我画了一些画,在画上画了一个高斯密度,然后画了那个坏男孩:

代码语言:javascript
复制
numDraws   <- 1e6
gammaDraws <- rgamma(numDraws, 2)
expDraws   <- rexp(numDraws)
combined   <- .5 * (gammaDraws + expDraws)
plot(density(combined))

输出应该看起来有点像这样:

票数 7
EN

Stack Overflow用户

发布于 2010-08-25 13:28:37

这里是在R中做卷积的尝试( @Jim Lewis指的是卷积)。请注意,可能有更有效的方法来做这件事。

代码语言:javascript
复制
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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3562811

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档