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.