Home > Back-end >  uniroot() of derivative D() in variable (or how to write an object as a function)
uniroot() of derivative D() in variable (or how to write an object as a function)

Time:09-22

I have a short question an hope someone can help me with it. I can't find a solution...

I want to use uniroot() to find the zero point of a function, or more exact from a derivative of a function. If I write the function as function(x).. this is no problem, but if I want to bring the derivate via a variable to the uniroot it will not.

#This will not work:
deriv1 <- D(expression(x^2-2*x),"x")
uniroot(deriv1, c(0,5))

# This will work:
func <- function(x) 2 * x - 2
uniroot(func, c(0,5))

Many Thanks in advance!

CodePudding user response:

You can construct a function with the derivate expression as body:

deriv1 <- D(expression(x^2-2*x),"x")
f <- function(x){}
body(f) <- deriv1
uniroot(f, c(0,5))

You could also use symbolic calculus instead of uniroot:

library(Ryacas)
fun <- yac_symbol("x^2-2*x")
dfun <- deriv(fun, "x")
solve(dfun, "x")
# {x==1} 

And to extract the solution:

yac_solution <- solve(dfun, "x")
solution <- yac_symbol(paste0("x Where ", solution))
yac(solution)
  •  Tags:  
  • r
  • Related