伽玛密度图:dgamma工作,而自己的函数返回错误

时间:2016-02-18 18:03:27

标签: r plot gamma-function

我试图为参数(形状)alfa = 3457和(rate)beta = 84绘制Gamma密度函数。如果我这样做:

curve(dgamma(x,shape=3457,rate=84),from=35,to=50,xlab="posterior theta",ylab="density")

一切正常,我的密度集中在~41。如果我首先将密度构造为:

para_density = function(x,s=3457,r=84,N) ((r^s)/(gamma(s)))*x^(s-1)*exp(-r*x)

然后将其绘制成:

curve(para_density(x,s=3457,r=84,N=N),from=0,to=100)

R告诉我gamma(s)返回Inf,鉴于其含义,这是明智的。

为什么我可以使用绘图和dgamma函数以相同的参数化绘制它?

提前感谢你们。

1 个答案:

答案 0 :(得分:1)

那么,只需使用logarithm

代码(未经测试!)

mygamma <- function(x, s, r) {
    l <- s*log(r) - lgamma(s) + (s-1.0)*log(x) - x*r
    exp(l)
}

更新

是的,它有效

library(ggplot2)

p <- ggplot(data = data.frame(x = 0), mapping = aes(x = x))
p <- p + stat_function(fun = function(x) dgamma(x,shape=3457,rate=84))
p <- p + stat_function(fun = function(x) mygamma(x,s=3457,r=84))
p <- p + xlim(35.0, 50.0)
print(p)

enter image description here