Reputation: 717
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.
Upvotes: 0
Views: 473
Reputation: 263411
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.
Upvotes: 1