Calculating the derivative in python 3

by Alex
Calculating the derivative in python 3

We will use the library SymPy to calculate derivatives. This is an open-source library written entirely in Python. It is developed as a computer algebra system.

Connecting SymPy

The first thing we need to do is to install the library. To do this, type in the terminal (command line) the command: pip install sympy. To connect the library in your Python 3 code, use the keyword import. To avoid having to prepend all the functions of sympy, I will connect it like this:

from sympy import *

Note that SymPy has many classes and functions with names that may overlap with those of other libraries. For example, if you use math library, it also has sin, cos, pi and others.

The formula for Russian roads

For example, let’s take a function with two independent variables, like surface y=f(x, z). Let’s use the Russian roads formula: y=sin(x)+0.5-z. Before we take the derivative of this function in Python, we have to declare all variables that will be used in it. To do that, use the symbols function. As an argument we use a string with variable names listed separated by commas or spaces.

x, z = symbols('x z')

After that, we take the partial derivative in Python 3 using the function diff. We write the function as the first argument, and the variable we are going to differentiate it by as the second argument. The result is printed with print.

The road up the hill

Let’s take the derivative over z:

from sympy import *
x, z = symbols('x z')
print(diff(sin(x)+0.5*z, z))


The result is 0.5. The partial derivative on z is positive, hence the road is uphill.

The road with the rut

Now let’s take the derivative of x:

from sympy import *
x, z = symbols('x z')
print(diff(sin(x)+0.5*z, x))


So the partial derivative of x equals cos(x). The tractor doesn’t care about the track, it only cares about the slope of the hill. Depending on the problem, we take the derivative for the desired parameter. In the diff function, if necessary, you can specify the order of differentiation as the third parameter. Since we calculated the first-order derivative, we did not specify it.

Related Posts