This article will cover some advanced mathematical functions provided by the Sympy library. If you still have not read the first introductory article to Sympy, you can check it out here.
Since most of the basic functions, like the ones for initiating a Sympy session on your terminal or for defining a function/variable, will not be covered in here.
In this article we will explore how to calculate derivatives, integrals and limits with Sympy and also how to plot graphs directly from the terminal. As already said in the previous article and video, the commands and functions that will be described in the following sections can be typed both in the script and in the terminal; I’ll use the terminal since it offers more intuitive and clearer data representation.
We start our code by importing the Sympy and Matplotlib libraries; we will use the latter library to create plots from our data. If you do not know or you simply do not remember these procedures, just have a look at the first article on Sympy, where it is also described how to initiate a Sympy session and define variables and functions().
Derivatives and partial derivatives
Calculating the derivatives of mathematical functions is a really common practice in most science related fields; by doing that, it is possible to identify the location of the maxima and minima of a function, i.e. the points in which it starts to increase/decrease.
Sympy allows to solve this task in a very immediate way; the function that is used to this purpose is called diff(), from “differential”. The function diff(), takes as input parameter the function that we want to derivate. In the following code lines, we define a function, “f”, and we calculate its first derivative.
>>> f = 3*x**2 + 4*x + 5 >>> diff(f) 6⋅x + 4
As you could see, in just one single line of code we managed to calculate the derivative of the function. In this case, it could be even possible to calculate the second derivative of “f” (it’s more correct to say that in this case the second derivative is not equal to zero), since it presents a second order term (x2).
To calculate the second or higher order derivatives of functions with Sympy, it is just sufficient to specify, after the function name, the variable with respect to which we want to make the derivation and the number of times we want to perform the differentiation (i.e. calculating the derivatives). In the following code lines, we calculate the second derivative of “f”, i.e. we differentiate the function twice.
>>> f 2 3⋅x + 4⋅x + 5 >>> diff(f, x, 2) 6
Also in this case, Sympy made the task awkwardly easy and immediate!
When we are dealing with multi-variable functions, we may be interested in calculating their partial derivatives; to do that, it is sufficient to specify the variable with respect to which we want to differentiate the function. In the following example, the function “g” is a three-variable function (x, y, z); we hence show how to calculate the partial derivatives with respect to each of three variables.
>>> g = 2*x + 4*y**2 - x*z >>> diff(g, x) 2 - z >>> diff(g, y) 8⋅y >>> diff(g, z) -x
Integrals
Integrating is the opposite operation compared to differentiating. From a graphical point of view, integrating a function means calculating the area between the function and the x-axis, but of course, the potential of Integral Calculus is not limited to just the areas beneath graphs.
In this section we will see firstly how to express an integral of a function in the terminal; as you will see, Sympy allows for a better representation of the function within the terminal.
To this purpose, we still use the “f” function defined at the beginning (you can find it also in the first lines of this code section) and we just define its integral, between the points -2 and 2. To do that, we exploit the function Integral() and pass as input parameters the function, the variable for which we want to integrate, followed by the lower and upper boundaries (these three latter parameters have to be put within parentheses).
>>> f 2 3⋅x + 4⋅x + 5 >>> Integral(f, (x, -2, 2)) 2 ⌠ ⎮ 2 ⎮ 3⋅x + 4⋅x + 5 dx ⌡ -2
At this stage, we have just expressed the integral that we want to solve, using the mathematical notation. However, what really interests us is how to actually solve the integral. To solve the integral, we use a function called integrate(); the input parameters are still the same; if you just want to solve the integral symbolically, you do not have to specify the integration limits. In the following code lines, we first solve the integral symbolically and then numerically by entering all the parameters already used with the function Integral().
>>> integrate(f) 3 2 x + 2⋅x + 5⋅x >>> integrate(f, (x, -2, 2)) 36
As you can see, thanks to the integrate() function, it was possible to solve the integral both symbolically and numerically in a very immediate way. With a similar approach, it is also possible to solve double or triple integrals; we just have to specify the boundaries for each variable, in the same way we did for the x variable in the example above; in the next code lines, we calculate the double integral of the function “g”.
>>> g = x**2 + 5*y >>> integrate(g, (x, -2, 2), (y, 3, 5)) 512/3
If we wanted to solve the integral symbolically with respect to just one of the two variables, it would have been sufficient to give as input that variable, right after the name of the function to integrate (“g” in this case).
Limits
In math, limits are used to evaluate a function when it approaches “critical” points in which it could diverge or converge to a specific values, being them a finite number or ± infinity. To calculate the limits of a mathematical function, we use the Sympy function limit(); it takes as input the function of interest, the variable to which the limit is referred to and the point in which we want to compute the limit, i.e. the point the independent variable “is approaching”. In the following example we evaluate the limit of the function sin(x)/x when x is approaching zero.
>>> limit(sin(x)/x, x, 0) 1
In some cases, the limits may assume different values whether the independent variable is approaching the critical point from higher or lower values; an example is the limit of the function 1/x, evaluated in the proximity of zero; as you will see, the result is different if we approach to zero from higher or lower numbers. To specify the direction from which we want to “approach” the critical point, we add another input parameter, that is “-“ or “+”, indicating that we are approaching that critical point from lower or higher values, respectively.
>>> limit(1/x, x, 0, '-') -∞ >>> limit(1/x, x, 0, '+') ∞
As predicted, the result of the limit in the two cases varies from –∞ to +∞.
Plotting functions
In this last section, we will explore another really useful feature of Sympy, that is the possibility to plot and hence display functions by just typing their equations, directly in the terminal. To accomplish this task, we should have previously installed Matplotlib (strictly speaking, this is not mandatory, Sympy is also able to represent the entire plot by using dots and lines; however, the graphical output is not the best; I personally recommend installing and exploit matplotlib). In the following examples, we will see just some of the most significant functions; however, keep in mind that there are lots of other different possibilities and options.
If you are interested in them, have a look at the official documentation here: https://docs.sympy.org/latest/modules/plotting.html
We start by looking at how to plot a single function; we firstly assign the plot to the variable “p1”; to plot the function, we use the function plot(), entering, as input parameters, the function (expressed explicitly) and the boundaries of the independent variable (this is not mandatory, if we do not specify any boundaries, the function will be displayed from -5 to +5).
>>> p1 = plot(3*x + 4, (x, -3, 3))
At this point, we should be able to see in a separate matplotlib window, the plot of our function; Figure 1 reports the outcome of the example.
Figure 1: Plot of the function f(x) = 3x + 4, calculated for values of x from -3 to +3.
It is also possible to plot multiple graphs in the same plot, each of them with its own boundaries; to do that, we just have to exploit the function extend(). In the following code lines, we define a second plot, “p2”, we choose to not show it by specifying in the option “show=False” and through the extend() function, we add it to the initial plot, p1. We finally show p1. The final outcome is displayed in Figure 2.
>>> p2 = plot(x**2, (x, 3, 7), show=False) >>> p1.extend(p2) >>> p1.show()
Figure 2: The plot “p2” (defined from x=3 to x=7) has been added and displayed together with the initial one (p1).
Another interesting feature of Sympy is the possibility of plotting parametric functions like circumferences. To do that, we can exploit the function plot_parametric(), its input parameters are the “x” and “y” coordinates of the points defining the parametric curve, the parametric variable and its boundaries. The following code lines show how to plot a circumference centered at the origin of the axes, with its independent variable varying from -7 to 7. Figure 3 displays the matplotlib window with the plot hence generated.
>>> plot_parametric((cos(x), sin(x)), (x, -7, 7))
Figure 3: Parametric representation of a circumference centered at the origin of the x and y axes.
The last function that we will explore allows you to plot functions giving as input parameter the equation in the implicit form. This feature could be really useful when dealing with really complex and long functions, for which is often difficult to obtain the explicit version (i.e. the one in which one variable is expressed as a function of all the others). To solve this task, the appropriate function is plot_implicit(); the input parameters are the implicit function (i.e. the one that displays both the variables in its equation) and the boundaries for each of the variables. In the following code lines, we plot a parabolic function, giving as input its implicit equation and changing the boundaries for both the x and the y coordinates. The final result is then shown in Figure 4.
>>> plot_implicit(x**2 + 2*y, (x, -2, 2), (y, -3, 3))
Figure 4: Plot of a parabolic function obtained by passing as input parameter its equation in the implicit form.
Conclusions
This article showed how to use Sympy for solving mathematical tasks like derivatives, integrals and limits. In the final part, Sympy was used to obtain plots of the functions directly from the terminal. All the code that was shown in the different sections has been typed into the terminal; however, the same results can be obtained by writing the same functions within the script. This was just a very brief introduction to the amazing capacity of the Sympy library, I strongly suggest you to check the official documentation page (https://www.sympy.org/en/index.html ), where you will find a plethora of other cool functions and options that could immediately offer an easy solution to most of your math problems.