Defining, symbolically, a function operating on arrays
Anybody that has written numerical code will know that a common source of mistakes is the definition of functions that evaluate a complicated formula. One way around this problem is to use a package for symbolic computations, and we will take advantage of sympy
, which is a compact Python symbolic package.
Getting ready
Note
If you are using Anaconda, sympy
is already installed on your system. Otherwise, you will have to install it by using pip3 install sympy
.
To see the full results of the following recipe, we assume that the reader is running Jupyter. Before getting started, run the following code in a Jupyter cell:
from sympy import * init_printing(use_latex=True)
This will load all sympy
functions and objects in the current namespace. This is usually not recommended, but in this example it is clearer to define the mathematical functions we will be using.
How to do it...
Let's now define the expression for the function we want to compute by...