# How to compute the derivative of a function

## Description

Given a mathematical function $f(x)$, we write $f’(x)$ or $\frac{d}{dx}f(x)$ to represent its derivative, or the rate of change of $f$ with respect to $x$. How can we compute $f’(x)$ using mathematical software?

## Using SymPy, in Python

View this solution alone.

This answer assumes you have imported SymPy as follows.

1
2
from sympy import *                   # load all math functions
init_printing( use_latex='mathjax' )  # use pretty math output


In SymPy, we tend to work with formulas (that is, mathematical expressions) rather than functions (like $f(x)$). So if we wish to compute the derivative of $f(x)=10x^2-16x+1$, we will focus on just the $10x^2-16x+1$ portion.

1
2
3
var( 'x' )
formula = 10*x**2 - 16*x + 1
formula


$\displaystyle 10 x^{2} - 16 x + 1$

We can compute its derivative by using the diff function.

1
diff( formula )


$\displaystyle 20 x - 16$

If it had been a multi-variable function, we would need to specify the variable with respect to which we wanted to compute a derivative.

1
2
3
var( 'y' )               # introduce a new variable
formula2 = x**2 - y**2   # consider the formula x^2 + y^2
diff( formula2, y )      # differentiate with respect to y


$\displaystyle - 2 y$

We can compute second or third derivatives by repeating the variable with respect to which we’re differentiating. To do partial derivatives, use multiple variables.

1
diff( formula, x, x )    # second derivative with respect to x


$\displaystyle 20$

1
diff( formula2, x, y )   # mixed partial derivative


$\displaystyle 0$

See a problem? Tell us or edit the source.

## Solution, in R

View this solution alone.

Let’s consider the function $f(x)=10x^2-16x+1$. We focus not on the whole function, but just the expression on the right-hand side, $10x^2-16x+1$.

1
formula <- expression( 10*x^2 - 16*x + 1 )


We can compute its derivative using the D function.

1
D( formula, "x" )   # derivative with respect to x

1
10 * (2 * x) - 16


R does not simplify the output, but if we do so ourselves, we find that $f’(x)=20x-16$.

If it had been a multi-variable function, we would need to specify the variable with respect to which we wanted to compute a derivative.

1
2
formula2 <- expression( x^2-y^2 )  # consider the formula x^2 - y^2
D( formula2, "y" )                 # differentiate with respect to y

1
-(2 * y)


That output says that $\frac{\partial}{\partial y}(x^2-y^2)=-2y$.

We can compute the second derivative by using the D function twice and specifying the variables with respect to which we are computing the derivative.

1
D( D( formula2, "x" ), "x" )  # second derivative with respect to x

1
 2

1
D( D( formula2, "x" ), "y" )  # mixed partial derivative

1
 0