ZgrKARALAR
ZgrKARALAR

Reputation: 489

Uniroot log(x) solution

I would like to find the root of log(x) = x2 − 2 using uniroot in R

f <- function(x)  (log(x)+2-x^2)
uniroot(f, lower=0, upper=100000000)$root

But this shows the error

Error in uniroot(f, lower = 0, upper = 1e+08) : f() values at end points not of opposite sign

Upvotes: 3

Views: 2290

Answers (1)

John Coleman
John Coleman

Reputation: 52008

uniroot requires an interval where the function has opposite signs at the two endpoints (since it uses a variation of the bisection method). It isn't a bad idea to do a quick plot when you don't know about just where to look:

f <- function(x)  (log(x)+2-x^2)
x <- seq(0.0,4,0.01)
y <- f(x)
plot(x,y,ylim = c(-1,1),type = "l")
abline(h=0)

This yields:

enter image description here

From this you can see that there are two roots, one between 0 and 1, and one between 1 and 2:

uniroot(f,interval = c(0,1))$root  #returns 0.1379346
uniroot(f,interval = c(1,2))$root  #returns 1.564445

Upvotes: 2

Related Questions