0

我试图找到以下使用uniroot()in的解决方案R

library(rootSolve)
set.seed(2)
y=rgamma(10,5,2)
myfun=function(y,t)as.numeric(integrate(function(x){ ((x^4) * exp(-x/2))/768 },0,upper=2)[1])-t
myfun(y, y)
final_fun=function(y)uniroot(myfun,c(-2, 2),tol=0.01,t=y)
final_fun(y)

但是,我收到以下错误。

 Error in uniroot(myfun, c(-2, 2), tol = 0.01, t = y) : 
  f() values at end points not of opposite sign 

我尝试了几个值upperlower限制,但R给出了相同的错误。我的问题是,如何找到正确的upperlower ?谢谢您的帮助。

4

1 回答 1

0

我不认为 y=t 参数会起作用,所以我通过使其成为一个变量的函数来以不同的方式定义函数(因为该y参数仅用于t为该函数内部提供一个值)。请注意,此表达式是一个常量:

 integrate(function(x){ ((x^4) * exp(-x/2))/768 },0,upper=2)
 $   ----> 0.00366 with absolute error < 4.1e-1:
# So that gives the same result as what was written above, regardless of y values

myfun=function(y)as.numeric(integrate(function(x){ ((x^4) * exp(-x/2))/768 },0,upper=2)[1])-y

 final_fun=function(y)uniroot(myfun,interval =c(-2, 2), tol=0.01)
 final_fun(y)
#----------------------
$root
[1] 0.00366

$f.root
[1] -1.7e-16

$iter
[1] 2

$init.it
[1] NA

$estim.prec
[1] 0.005

我也不认为这些值是从您创建y的 -object 中从全局环境中提取的。y由于您还没有真正解释要解决的问题,因此很难判断该解决方案对您是否有很大价值,但也许它会提供您可以使用的解决方案。

于 2021-08-01T17:32:04.277 回答