Question

I would like to evaluate higher order derivatives of some function f in R. Two possibilities are available to me.

  1. Either I determine a general expression for f(k), the k-th derivative of f (which I can do in my particular case), and then I evaluate it;
  2. Or I take advantage of the capacities of R to perform symbolic derivative (function D()).

What are the advantages of 1 over 2? Let us say that f(k) is not a recursive formula. What if f(k) is recursive?

Any hint will be appreciated.

Était-ce utile?

La solution

Symbolic differentiation is less error prone than doing it by hand.

For low orders I would not think that symbolic differentiation would take much computer time but you can readily time your specific situation to determine what it is using proc.time, system.time or the rbenchmark package. Also see these examples.

You might want to try both symbolic and hand differentiation as a check.

Regarding R's deriv (and associated functions such as D) vs. the Ryacas package, the latter has the facility to do repeated differentiation without requiring that the user iterate themselves (third arg of deriv specifies the order) and it has a Simplify function for which no counterpart exists in R although Ryacas should be carefully checked since yacas can be a bit buggy at times.

Here is an example:

> library(Ryacas)
> x <- Sym("x")
> y <- (x^2+x)^2
> dy <- deriv(y, x, 2) # 2nd deriv
> dy
expression(2 * (2 * x + 1)^2 + 4 * (x^2 + x))
> Simplify(dy)
expression(2 * (6 * x^2 + 6 * x + 1))

EDIT: Added to example:

> Eval(dy, list(x = 3))
[1] 146
> Eval(Simplify(dy), list(x = 3))
[1] 146
>
> f <- function(x) {}
> body(f) <- yacas(Simplify(dy))[[1]]
> f
function (x) 
2 * (6 * x^2 + 6 * x + 1)
> f(3)
[1] 146
>
> # double check
> w <- 3
> eval(D( D(expression((w^2+w)^2), "w"), "w"))
[1] 146

Also try demo("Ryacas-Function") .

EDIT 2: Fixed an error and added more to the example.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top