In this tutorial we will learn the basics of Jupyter and SymPy. SymPy is a Python library for symbolic computation. It provides computer algebra capabilities either as a standalone application, as a library to other applications, or live on the web as SymPy Live or SymPy Gamma. Sympy is similar to other CAS (Computer Algebra Software) like Mathematica, Maple or Maxima.
A more complete tutorial can be found at http://docs.sympy.org/latest/tutorial/index.html.
Before using SymPy we should load it, like any other Python libary. We will use
init_session()
to make some imports, this will help us in its interactive use.
For scripting it would be better to do the imports diffferently, for example
import sympy as sym
and then call the functions from SymPy in the following manner
x = sym.Symbols("x")
expr = sym.cos(x)**2 + 3*x
deriv = expr.diff(x)
where we computed the derivative of $cos^2(x) + 3x$, that should be $-2\sin(x)\cos(x) + 3$.
For further information on the Jupyter Notebook you can refer to the User Manual.
In [1]:
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
In [2]:
init_session()
plt.style.use("seaborn-notebook")
Let us start with some simple calculations. Belowe we have a code cell with an addition. Place the cursor on it and press SHIFT + ENTER to evaluate it.
In [3]:
1 + 3
Out[3]:
Let us make some calculations
In [4]:
factorial(5)
Out[4]:
In [5]:
Out[4]* 10
Out[5]:
In [6]:
1 // 3
Out[6]:
In [7]:
1 / 3
Out[7]:
In [8]:
S(1) / 3
Out[8]:
We can evaluate an expression to its floating point version
In [9]:
sqrt(2*pi)
Out[9]:
In [11]:
float(Out[9])
Out[11]:
In the previous line we used the expression Out[8] that stores the output from the evaluation in cell 8 (In[8]). We can also store expressions as variables, just as any Python variable.
In [12]:
radius = 10
height = 100
area = pi * radius**2
volume = area * height
In [13]:
volume
Out[13]:
In [14]:
float(volume)
Out[14]:
So far, we have just used SymPy as a calculator. Let us try more advanced calculations
Definite and indefinite integrals
In [15]:
integrate(sin(x), x)
Out[15]:
In [16]:
integrate(sin(x), (x, 0, pi))
Out[16]:
We can define a function and integrate it
In [17]:
f = lambda x: x**2 + 5
In [18]:
f(5)
Out[18]:
In [19]:
integrate(f(z), z)
Out[19]:
In [20]:
integrate(1/(x**2 + y), x)
Out[20]:
If we assume that the denominator is positive, the expression can be factorized further
In [21]:
a = symbols("a", positive=True)
integrate(1/(x**2 + a), x)
Out[21]:
We just learnt the basics, we can try some examples now.
Note: If you want to know more about a specific function you can use help()
or the IPython magic command ??
In [22]:
help(integrate)
In [23]:
integrate??
Right now, there are two main options for solution of algebraic systems, namely:
solveset
and solve
.
The preferred method is solveset
(see this
explanation, although
there are systems that can be solved using solve
and not solveset
.
To solve equations using solveset
:
In [24]:
a, b, c = symbols("a b c")
solveset(a*x**2 + b*x + c, x)
Out[24]:
We should enter the equations as equated to 0, or as an equation
In [25]:
solveset(Eq(a*x**2 + b*x, -c), x)
Out[25]:
Currently solveset is not capable of solving the following types of equations:
solve can be used for such cases:
In [26]:
solve([x*y - 1, x - 2], x, y)
Out[26]:
In [27]:
solve(x*exp(x) - 1, x )
Out[27]:
In [28]:
A = Matrix([
[1, -1],
[1, sin(c)]
])
display(A)
In [29]:
B = A.inv()
display(B)
In [30]:
A * B
Out[30]:
This should be the identity matrix, let us simplify the expression. There are several simplification functions, and simplify
is the most general one. Simplifying is a complicated matter... if you are uncertain; use simplify
.
In [31]:
simplify(A * B)
Out[31]:
In [32]:
%matplotlib inline
from sympy.plotting import plot3d
In [33]:
plot(sin(x), (x, -pi, pi));
In [34]:
monkey_saddle = x**3 - 3*x*y**2
p = plot3d(monkey_saddle, (x, -2, 2), (y, -2, 2))
In [35]:
f = lambda x: x**2
In [36]:
diff(f(x), x)
Out[36]:
In [37]:
f(x).diff(x)
Out[37]:
In [38]:
g = lambda x: sin(x)
In [39]:
diff(g(f(x)), x)
Out[39]:
Yes, SymPy knows about the chain rule.
To finish, let us solve a second order ODE
$$ u''(t) + \omega^2 u(t) = 0$$
In [40]:
u = symbols("u", cls=Function)
omega = symbols("omega", positive=True)
In [41]:
ode = u(t).diff(t, 2) + omega**2 * u(t)
dsolve(ode, u(t))
Out[41]:
In [42]:
f = lambdify(x, x**2, "numpy")
f(3)
Out[42]:
In [43]:
f(np.array([1, 2, 3]))
Out[43]:
We can try a more difficult one
In [44]:
fun = diff(sin(x)*cos(x**3) - sin(x)/x, x)
fun
Out[44]:
In [45]:
fun_numpy = lambdify(x, fun, "numpy")
and then evaluate it for some points in, let's say, $[0, 5]$
In [46]:
pts = np.linspace(0, 5, 1000)
fun_pts = fun_numpy(pts + 1e-6) # To avoid division by 0
In [47]:
plt.plot(pts, fun_pts);
The following cell change the style of the notebook.
In [49]:
from IPython.core.display import HTML
def css_styling():
styles = open('../styles/custom_barba.css', 'r').read()
return HTML(styles)
css_styling()
Out[49]:
In [ ]: