Working with simple derivatives in R

In only a few lines of R code we can differentiate a polynomial equation and use the derivative to find its vertices.


Define a function

Define the polynomial function \( y=f(x)=x^{3}+3x^{2}-6x-8 \)

f <- function(x) (x^3 + 3 * x^2 - 6 * x - 8)

Now plot the \( f(x) \) over the domain \( \{x | -5 > x > 4 \} \)

curve(f, -5, 4, ylab = "y=f(x)")

plot of chunk unnamed-chunk-2


Differentiate a function

Calculate the derivative \( g(x)=\frac{\partial x}{\partial y} \)

g <- function(x) {}
body(g) <- D(body(f), 'x')

The derivative of \( f(x) \) is:

body(g)
## 3 * x^2 + 3 * (2 * x) - 6

Plot the derivative.

curve(g, -5, 4, ylab = "g(x)")

plot of chunk unnamed-chunk-5


Calculate roots of a function

Calulate the roots of \( g(x) \).

library(rootSolve)
roots <- multiroot(g, c(-5, 4))

The roots of \( g(x) \) are:

print(roots$root)
## [1] -2.7321  0.7321

Find the vertices of a function

Evaluate \( f(x) \) at the roots of \( g(x) \).

f(roots$root)
## [1]  10.39 -10.39

Highlight the vertices of \( f(x) \).

curve(f, -5, 4, ylab = "y=f(x)")
points(f(roots$root) ~ roots$root)

plot of chunk unnamed-chunk-9