# Symbolic math¶

## Library¶

In [1]:
import sympy as sp
sp.init_printing()                     # to get pretty output
from IPython.display import display    # can use display instead of print for nice output


## Tutorial¶

Here is a link to a great sympy tutorial. These notes follow the tutorial.

## Define symbols¶

In [48]:
x, y, z = sp.symbols('x, y, z')


## Expressions¶

In [50]:
ex1 = x*sp.cos(x)           # note, expressions are immutable
ex2 = x**2 + y**2 + z
ex3 = sp.sqrt(x+y/2)

display(ex1)
display(ex2)
ex3

$\displaystyle x \cos{\left(x \right)}$
$\displaystyle x^{2} + y^{2} + z$
Out[50]:
$\displaystyle \sqrt{x + \frac{y}{2}}$

### Substite a number or symbol in an expression¶

In [4]:
ans1 = ex1.subs(x, 1.0)          # give 1.0 evaluates numerically
ans2 = ex1.subs(x, 1)            # treats 1 as a symbol
ans3 = ex1.subs(x, y)
ans4 = ex1.subs(x, y**2+z)

display(ans1)
display(ans2)
display(ans3)
display(ans4)

$\displaystyle 0.54030230586814$
$\displaystyle \cos{\left(1 \right)}$
$\displaystyle y \cos{\left(y \right)}$
$\displaystyle \left(y^{2} + z\right) \cos{\left(y^{2} + z \right)}$
• You can sub more than one thing:
In [5]:
ex = x**2 + 2*x*z - y

ex.subs( [(x,4.5), (y,2.2)] )

Out[5]:
$\displaystyle 9.0 z + 18.05$
• You can also use the evalf function to get numeric results.
In [6]:
ex = x**2 + y

ex.evalf(subs={x: 3, y: 4})

Out[6]:
$\displaystyle 13.0$
In [54]:
sp.pi.evalf(100)

Out[54]:
$\displaystyle 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068$

### Simplify¶

In [8]:
ex = (x**2 + 3*x + 2)/(x+1)

ex.simplify()                 # these are all the same
sp.simplify(ex)
sp.simplify((x**2+3*x+2)/(x+1))

Out[8]:
$\displaystyle x + 2$

### Expand¶

In [9]:
ex = (x+2)*(x-3)

ex.expand()                  # these are all the same
sp.expand(ex)
sp.expand( (x+2)*(x-3) )

Out[9]:
$\displaystyle x^{2} - x - 6$

### Factor¶

In [10]:
ex = x**3 - x**2 + x - 1

ex.factor()
sp.factor(ex)
sp.factor( x**3 - x**2 + x - 1 )

Out[10]:
$\displaystyle \left(x - 1\right) \left(x^{2} + 1\right)$

### Others:¶

• collect
• cancel
• apart
• trigsimp
• expand_trig
• powsimp
• expand_power_exp
• expand_power_base
• pow_denest
• expand_log
• logcombine
• etc.

## Calculus¶

### Derivatives¶

In [11]:
ex = sp.exp(x**2)

ex.diff(x)                    # these are the same
sp.diff(ex, x)
sp.diff(sp.exp(x**2), x)

Out[11]:
$\displaystyle 2 x e^{x^{2}}$
In [12]:
sp.diff(x**4, x,x,x)          # take the third derivative (note extra x's)

Out[12]:
$\displaystyle 24 x$

Take the following derivative: $$\frac{\partial^3}{\partial x\partial y\partial z}e^{xyz}.$$

In [13]:
ex = sp.exp(x*y*z)
sp.diff(ex, x,y,z)

Out[13]:
$\displaystyle \left(x^{2} y^{2} z^{2} + 3 x y z + 1\right) e^{x y z}$
• The Derivative function doesn't evaluate the derivative, it is just used for making an expression.
• To evaluate it use the doit function.
In [14]:
ex = sp.exp(x*y*z)

my_der = sp.Derivative(ex, x, y, z)    # ex.Derivative(x,y,z) doesn't work
my_der

Out[14]:
$\displaystyle \frac{\partial^{3}}{\partial z\partial y\partial x} e^{x y z}$
In [15]:
my_der.doit()                 # now evaluate the derivative

Out[15]:
$\displaystyle \left(x^{2} y^{2} z^{2} + 3 x y z + 1\right) e^{x y z}$

### Integrals¶

• integrate function evaluates and integral
• Integral function creates an integral expression
• doit function evaluates an integral expression
In [16]:
sp.integrate(x**2, x)

Out[16]:
$\displaystyle \frac{x^{3}}{3}$

Integrate this: $$\int_0^{\infty}e^{-x}dx.$$

In [17]:
sp.integrate(sp.exp(-x), (x,0,sp.oo))    # infinity is "oo": double o's

Out[17]:
$\displaystyle 1$
In [18]:
sp.integrate(x*sp.exp(-x), (x,y,sp.oo))

Out[18]:
$\displaystyle - \left(- y - 1\right) e^{- y}$

Do a double integral: $$\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}e^{-x^2-y^2}dxdy.$$

In [19]:
sp.integrate(sp.exp(-x**2-y**2), (x,-sp.oo,sp.oo), (y,-sp.oo,sp.oo))

Out[19]:
$\displaystyle \pi$
In [20]:
ex = sp.Integral(sp.log(x)**2, x)

ex

Out[20]:
$\displaystyle \int \log{\left(x \right)}^{2}\, dx$
In [21]:
ex.doit()

Out[21]:
$\displaystyle x \log{\left(x \right)}^{2} - 2 x \log{\left(x \right)} + 2 x$
In [22]:
ex = sp.Integral(sp.log(x)**2, (x,0,2))
ex

Out[22]:
$\displaystyle \int\limits_{0}^{2} \log{\left(x \right)}^{2}\, dx$
In [23]:
ex.doit()

Out[23]:
$\displaystyle - 4 \log{\left(2 \right)} + 2 \log{\left(2 \right)}^{2} + 4$
In [24]:
ex.doit().evalf()

Out[24]:
$\displaystyle 2.18831730559662$

### Limits¶

• Use the limit function to evaluate a limit,
• Also Limit to create a limit expression,
• doit to evaluate a limit expression

Evaluate $$\lim_{x\rightarrow 0}\frac{\sin(x)}{x}.$$

In [25]:
sp.limit(sp.sin(x)/x, x,0)

Out[25]:
$\displaystyle 1$

## Solvers¶

In [26]:
sp.solve(x**2-y, x)

Out[26]:
$\displaystyle \left[ - \sqrt{y}, \ \sqrt{y}\right]$

The above was in the form $f(x)=0$. If we have instead $x^2=1$, then use the Eq function

In [27]:
ex = sp.Eq(x**2,y)                # creates expression x^2 = 1

sp.solve(ex, x)                   # these are the same
sp.solve(sp.Eq(x**2,y), x)

Out[27]:
$\displaystyle \left[ - \sqrt{y}, \ \sqrt{y}\right]$

### Systems of equations¶

Solve this: \begin{align} x-y+2 &=0 \\ x+y-3 &=0 \end{align}

In [28]:
sp.solve( (x-y+2, x+y-3), (x, y))

Out[28]:
$\displaystyle \left\{ x : \frac{1}{2}, \ y : \frac{5}{2}\right\}$

Solve this: \begin{align} xy-7 &=0 \\ x+y-6 &= 0 \end{align}

In [29]:
sp.solve( (x*y-7, x+y-6), (x,y) )

Out[29]:
$\displaystyle \left[ \left( 3 - \sqrt{2}, \ \sqrt{2} + 3\right), \ \left( \sqrt{2} + 3, \ 3 - \sqrt{2}\right)\right]$

### Solve differential equations¶

• Use function dsolve
• Need to define a function symbol.
In [55]:
f = sp.Function('f')         # define a symbol for holding a function
f(x)                         # can also use f,g = sp.symbols('f,g', cls=Function)

Out[55]:
$\displaystyle f{\left(x \right)}$
In [56]:
f(x).diff(x)                 # these are the same
sp.diff(f(x), x)

Out[56]:
$\displaystyle \frac{d}{d x} f{\left(x \right)}$
In [57]:
f(x).diff(x,x)               # second derivative

Out[57]:
$\displaystyle \frac{d^{2}}{d x^{2}} f{\left(x \right)}$

Setup and solve this equation: $$f^{\prime\prime}(x) - 2f^{\prime}(x)+f(x)= \sin(x).$$

In [68]:
my_diffeq = sp.Eq(f(x).diff(x,x) - 2*f(x).diff(x) + f(x), sp.sin(x))
my_diffeq

Out[68]:
$\displaystyle f{\left(x \right)} - 2 \frac{d}{d x} f{\left(x \right)} + \frac{d^{2}}{d x^{2}} f{\left(x \right)} = \sin{\left(x \right)}$
In [69]:
sp.dsolve(my_diffeq, f(x))

Out[69]:
$\displaystyle f{\left(x \right)} = \left(C_{1} + C_{2} x\right) e^{x} + \frac{\cos{\left(x \right)}}{2}$

## Matrices¶

### Functions¶

• Matrix
• shape
• row
• col
• col_del
• row_del
• col_insert
• row_insert
• T for transpose
• zeros(m,n)
• ones(m,n)
• diag
• nullspace
• eigenvals
• diagonalize
• rref
In [35]:
A = sp.Matrix( [ [1,-1], [3,4], [0,2] ] )
A

Out[35]:
$\displaystyle \left[\begin{matrix}1 & -1\\3 & 4\\0 & 2\end{matrix}\right]$
In [36]:
b = sp.Matrix([1,2])     # assumes a column vector
b

Out[36]:
$\displaystyle \left[\begin{matrix}1\\2\end{matrix}\right]$
In [37]:
A.shape

Out[37]:
$\displaystyle \left( 3, \ 2\right)$
In [38]:
A.row(1)

Out[38]:
$\displaystyle \left[\begin{matrix}3 & 4\end{matrix}\right]$
In [39]:
A.row_del(0)
A

Out[39]:
$\displaystyle \left[\begin{matrix}3 & 4\\0 & 2\end{matrix}\right]$
In [40]:
x = A**-1 * b
x

Out[40]:
$\displaystyle \left[\begin{matrix}-1\\1\end{matrix}\right]$
In [41]:
A*x                 # should equal b

Out[41]:
$\displaystyle \left[\begin{matrix}1\\2\end{matrix}\right]$

### Symbolic matrix solution¶

In [42]:
m11, m12, m21, m22 = sp.symbols("m11, m12, m21, m22")
b1, b2             = sp.symbols("b1, b2")

In [43]:
A = sp.Matrix([ [m11, m12], [m21, m22] ])
b = sp.Matrix([b1,b2])

In [44]:
A

Out[44]:
$\displaystyle \left[\begin{matrix}m_{11} & m_{12}\\m_{21} & m_{22}\end{matrix}\right]$
In [45]:
b

Out[45]:
$\displaystyle \left[\begin{matrix}b_{1}\\b_{2}\end{matrix}\right]$
In [46]:
A.inv()*b        # these are the same
A**-1 * b

Out[46]:
$\displaystyle \left[\begin{matrix}\frac{b_{1} m_{22}}{m_{11} m_{22} - m_{12} m_{21}} - \frac{b_{2} m_{12}}{m_{11} m_{22} - m_{12} m_{21}}\\- \frac{b_{1} m_{21}}{m_{11} m_{22} - m_{12} m_{21}} + \frac{b_{2} m_{11}}{m_{11} m_{22} - m_{12} m_{21}}\end{matrix}\right]$
In [ ]: