Chapter 6Numerical differentiation and integration

6.1 Numerical differentiation

6.1.1 Numerical differentiation using base R

6.1.1.1 Using the fundamental definition

Calculating numerical derivatives is straightforward using a finite difference version of the fundamental definition of a derivative:

df(x)dx=limh0f(x+h)-f(x)h(6.1)

For example,

> f = function(x) x^3 * sin(x/3) * log(sqrt(x)
> x0 = 1; h = 1e-5
> (f(x0+h) - f(x0))/h
[1] 0.163603

while the true value of the derivative is 12sin(13)=0.163597348398076...

With h positive, this is called the forward derivative, otherwise it is the backward derivative. To take into account the slopes both before and after the point x, the central difference formula is chosen,

df(x)dx=limh0f(

Get Using R for Numerical Analysis in Science and Engineering now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.