R中“积分"函数中的“非有限"函数值错误 [英] 'non-finite' function value error in 'integrate' function in R

查看:92
本文介绍了R中“积分"函数中的“非有限"函数值错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个名为fun5"的函数,如下所示:

I defined a function called 'fun5' as follows:

function(y,mu=mu0,lsig=lsig0) {
  res = exp(y)/(1+exp(y)) * 1/sqrt(2*pi)/exp(lsig) * exp(-(y-mu)^2/2/exp(lsig)^2)
  return(res)

,然后用两个参数将函数从负无穷大到正无穷大.

, then integrated the function from negative infinity to positive infinity with two parameters.

integrate(fun5,-Inf,Inf,mu=2.198216,lsig=-3)$value

这个积分给出了一个随机变量的期望,它具有对数正态分布,mu = 2.198216,sigma = exp(-3).

This integral gives the expectation of a random variable which has logit-normal distribution with mu = 2.198216 and sigma = exp(-3).

发生此错误.

Error in integrate(fun5, -Inf, Inf, mu = 2.198216, lsig = -3) : 
  non-finite function value

由于函数 'fun5' 是一个介于 0 和 1 之间的随机变量乘以概率密度,它在任何地方都应该是正的,尽管它可能非常接近于零.我不明白为什么它在某处具有非有限值.

Since the function 'fun5' is a random variable between 0 and 1 multiplied by probability density, it should be positive everywhere, though it might be very close to zero. I don't understand why it has non-finite value somewhere.

谁能给点建议?

推荐答案

问题在于函数

exp(y)/(1+exp(y)) 

当 y 太大时四舍五入为 NaN.当 y 太大时,您可以避免将其替换为 1.这个函数会起作用:

is rounded to NaN when y is too big. You can avoid this replacing it with 1 when y is too big. This function will play the trick:

fun5<-function(y,mu=mu0,lsig=-lsig0) {
res = ifelse(y<100, exp(y)/(1+exp(y)) * 1/sqrt(2*pi)/exp(lsig) * exp(-(y-mu)^2/2/exp(lsig)^2),
             1/sqrt(2*pi)/exp(lsig) * exp(-(y-mu)^2/2/exp(lsig)^2))
return(res)}

现在这将起作用

integrate(fun5,-Inf,Inf,mu=2.198216,lsig=-3)$value
[1] 0.9

这篇关于R中“积分"函数中的“非有限"函数值错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆