How to compute the derivative of a function (in Python, using SymPy)
Task
Given a mathematical function
Solution
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
1
2
3
var( 'x' )
formula = 10*x**2 - 16*x + 1
formula
We can compute its derivative by using the diff
function.
1
diff( formula )
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
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
1
diff( formula2, x, y ) # mixed partial derivative
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Nathan Carter (ncarter@bentley.edu)