0

I trying to find the solution of the following using 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)

However, I am getting the following errors.

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

I tried several values for upper and lower limits, but R is giving the same errors. My question is, how to find the correct upper and lower values? Thanks for the help.

score324
  • 687
  • 10
  • 18
  • 1
    Try plotting your `myfun` to identify where its zeroes might be. Are you sure it even has zeroes? – Limey Aug 01 '21 at 06:57
  • @Limey From the context, I'm guessing that the OP thought that the y parameter in the uniroot function would be picking up values from the y's created by the rgamma call (but they would not be.) I'm wondering if the intent was to find a zero along a line of identity, but it's hard to tell. Might need to be closed if the OP doesn't respond by tomorrow. – IRTFM Aug 01 '21 at 23:16

1 Answers1

0

I didn't think that the y=t argument would work so I defined the function differently by making it a function of one variable (since the y argument was only used to provide a value to t inside that function). And note that this expression is a constant:

 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

I also don't think that the y values are being pulled in from the global environment from the y-object that you created. Since you haven't actually explained what problem is being solved, it's difficult to tell whether this solution has much value to you, but perhaps it will provide a solution you can work with.

IRTFM
  • 258,963
  • 21
  • 364
  • 487