Symbolic Computation

In [1]:
import addutils.toc ; addutils.toc.js(ipy_notebook=True)
Out[1]:

Symbolic computation (also called computer algebra) emphasizes exact computation where mathematical expressions and objects are represented by algebraic formulas, and not numbers. SymPy is the python module suitable for symbolic computation. See Sympy Modules Reference.

In [2]:
from addutils import css_notebook
from sympy import *
import numpy as np
import bokeh.plotting as bk
from bokeh.plotting import output_notebook
init_printing(use_latex='mathjax')
css_notebook()
Out[2]:
In [3]:
output_notebook()
Loading BokehJS ...

1 Basic manipulation

In [4]:
a, b, c = symbols('a, b, c')
exp1 = pi*( a*b*b+2*b*a*b )**c
exp1
Out[4]:
$$\pi \left(3 a b^{2}\right)^{c}$$

We can add assumpions to symbols

In [5]:
k = symbols('k', real=True, positive=True)
k > 0
Out[5]:
$$\mathrm{True}$$

Rational numbers

In [6]:
r1 = Rational(5,6)
r2 = Rational(7,3)
r1+r2
Out[6]:
$$\frac{19}{6}$$

The expression may be calculated by substituting numerical values to given variables (in this case --> a,b):

In [7]:
exp1.evalf(subs={a:6e-3, b:3, c:2})
Out[7]:
$$0.0824479576008105$$

We can combine expressions and Numpy arrays

In [8]:
b_vec = np.arange(0, 10, 0.1)
y_vec = np.array([exp1.evalf(subs={a:6e-3, b:bb, c:2}) for bb in b_vec])
y_vec = np.float64(y_vec)
fig = bk.figure(title=None)
fig.line(b_vec, y_vec)
bk.show(fig)

However, this kind of numerical evolution can be very slow, and there is a much more efficient way to do it: Use the function lambdify to "compile" a Sympy expression into a function that is much more efficient to evaluate numerically:

In [9]:
f = lambdify([b], exp1, 'numpy')
y_vec = f(b_vec)

2 Solve

Algebraically solve equations or systems of equations (expr = 0)

In [10]:
x, y, z = symbols("x y z")
e = (x+y)*40-(z-x)/0.5
e
Out[10]:
$$42.0 x + 40 y - 2.0 z$$
In [11]:
solve(e)
Out[11]:
$$\left [ \left \{ x : - 0.952380952380952 y + 0.0476190476190476 z\right \}\right ]$$

3 Algebra

3.1 Expand and Factor

In [12]:
exp2 = (x+1)*sin(x+2)*tanh(x+3)
exp2
Out[12]:
$$\left(x + 1\right) \sin{\left (x + 2 \right )} \tanh{\left (x + 3 \right )}$$
In [13]:
expand(exp2)
Out[13]:
$$x \sin{\left (x + 2 \right )} \tanh{\left (x + 3 \right )} + \sin{\left (x + 2 \right )} \tanh{\left (x + 3 \right )}$$

The expand function takes a number of keywords arguments which we can tell the functions what kind of expansions we want to have performed. For example, to expand trigonometric expressions, use the trig=True keyword argument (see help(sym.expand) for more info):

In [14]:
expand(exp2, trig=True)
Out[14]:
$$- x \sin{\left (x \right )} \tanh{\left (x + 3 \right )} + 2 x \sin{\left (x \right )} \cos^{2}{\left (1 \right )} \tanh{\left (x + 3 \right )} + 2 x \sin{\left (1 \right )} \cos{\left (1 \right )} \cos{\left (x \right )} \tanh{\left (x + 3 \right )} - \sin{\left (x \right )} \tanh{\left (x + 3 \right )} + 2 \sin{\left (x \right )} \cos^{2}{\left (1 \right )} \tanh{\left (x + 3 \right )} + 2 \sin{\left (1 \right )} \cos{\left (1 \right )} \cos{\left (x \right )} \tanh{\left (x + 3 \right )}$$

The opposite a product expansion is of course factoring. The factor an expression in SymPy use the factor function:

In [15]:
factor(x**3 + 6 * x**2 + 11*x + 6)
Out[15]:
$$\left(x + 1\right) \left(x + 2\right) \left(x + 3\right)$$

3.2 Symplify

The simplify tries to simplify an expression into a nice looking expression, using various techniques. More specific alternatives to the simplify functions also exists: trigsimp, powsimp, logcombine, etc.

The basic usages of these functions are as follows:

In [16]:
simplify(sin(x)**2 + cos(x)**2)
Out[16]:
$$1$$
In [17]:
simplify(sin(x)/cos(x))
Out[17]:
$$\tan{\left (x \right )}$$

3.3 apart and together

In [18]:
exp3 = 1/((a+1)*(a+2))
exp3
Out[18]:
$$\frac{1}{\left(a + 1\right) \left(a + 2\right)}$$
In [19]:
apart(exp3)
Out[19]:
$$- \frac{1}{a + 2} + \frac{1}{a + 1}$$
In [20]:
exp4 = 1/(a+2) + 1/(a+3)
exp4
Out[20]:
$$\frac{1}{a + 3} + \frac{1}{a + 2}$$
In [21]:
together(exp4)
Out[21]:
$$\frac{2 a + 5}{\left(a + 2\right) \left(a + 3\right)}$$

4 Calculus

4.1 Differentiation and Integration

In [22]:
exp2
Out[22]:
$$\left(x + 1\right) \sin{\left (x + 2 \right )} \tanh{\left (x + 3 \right )}$$
In [23]:
diff(exp2)
Out[23]:
$$\left(x + 1\right) \left(- \tanh^{2}{\left (x + 3 \right )} + 1\right) \sin{\left (x + 2 \right )} + \left(x + 1\right) \cos{\left (x + 2 \right )} \tanh{\left (x + 3 \right )} + \sin{\left (x + 2 \right )} \tanh{\left (x + 3 \right )}$$
In [24]:
exp4
Out[24]:
$$\frac{1}{a + 3} + \frac{1}{a + 2}$$
In [25]:
integrate(exp3, a)
Out[25]:
$$\log{\left (a + 1 \right )} - \log{\left (a + 2 \right )}$$
In [26]:
integrate(exp(-x**2), (x, -oo, oo))
Out[26]:
$$\sqrt{\pi}$$

4.2 Sum and Products

In [27]:
n = Symbol("n")
exp5 = 1/n**2
exp5
Out[27]:
$$\frac{1}{n^{2}}$$
In [28]:
Sum(exp5, (n, 1, oo))
Out[28]:
$$\sum_{n=1}^{\infty} \frac{1}{n^{2}}$$
In [29]:
Sum(exp5, (n, 1, oo)).evalf()
Out[29]:
$$1.64493406684823$$
In [30]:
Product(exp5, (n, 1, oo))
Out[30]:
$$\prod_{n=1}^{\infty} \frac{1}{n^{2}}$$

4.3 Limits

In [31]:
limit(1/x, x, 0, dir="+")
Out[31]:
$$\infty$$
In [32]:
limit(1/x, x, 0, dir="-")
Out[32]:
$$-\infty$$

4.4 Series

By default it expands the expression around $x=0$, but we can expand around any value of $x$ by explicitly include a value in the function call. It's possible to specify to which order the series expansion should be carried out:

In [33]:
exp6 = exp(x)
series(exp6, x)
Out[33]:
$$1 + x + \frac{x^{2}}{2} + \frac{x^{3}}{6} + \frac{x^{4}}{24} + \frac{x^{5}}{120} + \mathcal{O}\left(x^{6}\right)$$
In [34]:
series(exp(x), x, 1, 10)
Out[34]:
$$e + e \left(x - 1\right) + \frac{e}{2} \left(x - 1\right)^{2} + \frac{e}{6} \left(x - 1\right)^{3} + \frac{e}{24} \left(x - 1\right)^{4} + \frac{e}{120} \left(x - 1\right)^{5} + \frac{e}{720} \left(x - 1\right)^{6} + \frac{e}{5040} \left(x - 1\right)^{7} + \frac{e}{40320} \left(x - 1\right)^{8} + \frac{e}{362880} \left(x - 1\right)^{9} + \mathcal{O}\left(\left(x - 1\right)^{10}; x\rightarrow 1\right)$$

5 Linear algebra

5.1 Matrices

In [35]:
m11, m12, m21, m22 = symbols("m11, m12, m21, m22")
b1, b2 = symbols("b1, b2")
A = Matrix([[m11, m12],[m21, m22]])
A
Out[35]:
$$\left[\begin{matrix}m_{11} & m_{12}\\m_{21} & m_{22}\end{matrix}\right]$$
In [36]:
b = Matrix([[b1], [b2]])
b
Out[36]:
$$\left[\begin{matrix}b_{1}\\b_{2}\end{matrix}\right]$$
In [37]:
A * b
Out[37]:
$$\left[\begin{matrix}b_{1} m_{11} + b_{2} m_{12}\\b_{1} m_{21} + b_{2} m_{22}\end{matrix}\right]$$
In [38]:
A.det()
Out[38]:
$$m_{11} m_{22} - m_{12} m_{21}$$
In [39]:
A.inv()
Out[39]:
$$\left[\begin{matrix}\frac{m_{22}}{m_{11} m_{22} - m_{12} m_{21}} & - \frac{m_{12}}{m_{11} m_{22} - m_{12} m_{21}}\\- \frac{m_{21}}{m_{11} m_{22} - m_{12} m_{21}} & \frac{m_{11}}{m_{11} m_{22} - m_{12} m_{21}}\end{matrix}\right]$$

6 Solving Equations

In [40]:
exp7 = x**4 - x**2 - a
exp7
Out[40]:
$$- a + x^{4} - x^{2}$$
In [41]:
solve(exp7,x)
Out[41]:
$$\left [ - \sqrt{- \frac{1}{2} \sqrt{4 a + 1} + \frac{1}{2}}, \quad \sqrt{- \frac{1}{2} \sqrt{4 a + 1} + \frac{1}{2}}, \quad - \sqrt{\frac{1}{2} \sqrt{4 a + 1} + \frac{1}{2}}, \quad \sqrt{\frac{1}{2} \sqrt{4 a + 1} + \frac{1}{2}}\right ]$$

Visit www.add-for.com for more tutorials and updates.

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.