Numerical derivatives with grad
- Derivatives of many functions can be found analytically. The figure shows how to find the derivative of \(x^2\) using only the definition and elementary algebra.
- Here, however, we will focus on estimating derivatives numerically, using the function,
grad
, in package numDiff. (The name is a short form of “gradient,” a term which will be explained later.)
grad
takes two arguments, a function and a point at which the derivative of the function is to be estimated.
- For instance
grad(function(x)x^2, 1)
will estmate the derivative of x^2
at x=1. You know from the analytic derivation that this should be 2.
- In the example, grad’s first argument,
function(x)x^2
is an R function which takes one numerical argument and returns the value x^2
at the point x
represented by that argument.
- Using common functions such as cos, sin, exp, log, 1/x, have students compare their numerical and analytic derivatives. The follow code illustrates how that might be done. Note that
grad
is vectorized for functions of 1 variable but has nothing analogous for functions of several. I think that is confusing, but vectorization comes in handy here.
# Show that the derivative of sin is cos.
x <- seq(0, 2*pi, by=.2)
# swirl does this
plot(x, cos(x), type='l', lwd=2, xlab="x", ylab="sin(x)", main=expression(over(d, d*x)~~sin(x) == cos(x)))
abline(h=0)
legend('bottomleft', "cos(x)", lwd=2, cex=1.5)
legend('bottomright', expression(over(d, d*x)~~sin(x)), pch=19, col="blue", cex=1.5)
# student does this
deriv <- grad(sin, x)
points(x, deriv, pch=19, col="blue", cex=1.5)