## 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:

$$\begin{array}{cc}\frac{df\left(x\right)}{dx}=\underset{h\mathrm{\to}0}{\mathrm{lim}}\frac{f\left(x\mathrm{+}h\right)\mathrm{-}f\left(x\right)}{h}& \left(6.1\right)\end{array}$$

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 $\frac{1}{2}\mathrm{sin}\left(\frac{1}{3}\right)=0.163597348398076\mathrm{\text{...}}$

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,

$$\begin{array}{c}\frac{df\left(x\right)}{dx}=\underset{h\mathrm{\to}0}{\mathrm{lim}}\frac{f(}{}\end{array}$$

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.