Python - SymPy, and $\LaTeX$


In [ ]:
%matplotlib inline

import sympy as sp
import numpy as np
import matplotlib.pyplot as plt

Symbolic Mathematics (SymPy)


In [ ]:
sp.init_printing()     # Turns on pretty printing

In [ ]:
np.sqrt(8)

In [ ]:
sp.sqrt(8)

You have to explicitly tell SymPy what symbols you want to use.


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

Expressions are then able use these symbols


In [ ]:
my_equation = 2 * x + y
my_equation

In [ ]:
my_equation + 3

In [ ]:
my_equation - x

In [ ]:
my_equation / x

SymPy has all sorts of ways to manipulates symbolic equations


In [ ]:
sp.simplify(my_equation / x)

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

In [ ]:
sp.expand(another_equation)

In [ ]:
long_equation = 2*y*x**3 + 12*x**2 - x + 3 - 8*x**2 + 4*x + x**3 + 5 + 2*y*x**2 + x*y
long_equation

In [ ]:
sp.collect(long_equation,x)

In [ ]:
sp.collect(long_equation,y)

And solve equations - solve


In [ ]:
yet_another_equation = 2 * x**2 - 5 * x + 30

yet_another_equation

In [ ]:
sp.solve(yet_another_equation,x)

Calculus


In [ ]:
yet_another_equation

In [ ]:
sp.diff(yet_another_equation,x)

In [ ]:
sp.diff(yet_another_equation,x,2)

In [ ]:
sp.integrate(yet_another_equation,x)

In [ ]:
sp.integrate(yet_another_equation,(x,0,5))   # limits x = 0 to 5

Taylor Expansions


In [ ]:
still_another_equation = sp.sin(x) * sp.exp(-x)
still_another_equation

In [ ]:
sp.series(still_another_equation, x)

In [ ]:
sp.series(still_another_equation, x, x0 = 0, n = 8)

In [ ]:
sp.series(still_another_equation, x, x0 = sp.pi, n = 8)

Limits

$$\lim _{x\to \infty }\left(1+{\frac {1}{x}}\right)^{x}$$

In [ ]:
limit_equation = (1 + (1 / x)) ** x

limit_equation

In [ ]:
sp.limit(limit_equation, x, sp.oo)      # sp.oo = infinity

System of equations

$$ \begin{array}{c} x + 3y + 5z = 10 \\ 2x + 5y + z = 8 \\ 2x + 3y + 8z = 3 \\ \end{array} \hspace{3cm} \left[ \begin{array}{ccc} 1 & 3 & 5 \\ 2 & 5 & 1 \\ 2 & 3 & 8 \end{array} \right] \left[ \begin{array}{c} x\\ y\\ z \end{array} \right] = \left[ \begin{array}{c} 10\\ 8\\ 3 \end{array} \right] $$

In [ ]:
AA = sp.Matrix([[1,3,5],[2,5,1],[2,3,8]])
bb = sp.Matrix([[10],[8],[3]])

In [ ]:
AA, bb

In [ ]:
AA**-1

In [ ]:
AA**-1 * AA

In [ ]:
AA**-1 * bb

General Equation Solving - nsolve

$$ \large y_1 = 10\,\sin(5x) \ e^{-x}\\ \large y_2 = 6 - e^{0.75x} $$

Where do they cross? - The graph


In [ ]:
my_x = np.linspace(0,2*np.pi,100)

In [ ]:
my_y1 = 10 * np.sin(5*my_x) * np.exp(-my_x)
my_y2 = 6 - np.exp(0.75 * my_x)

In [ ]:
fig,ax = plt.subplots(1,1)
fig.set_size_inches(10,4)

fig.tight_layout()

ax.set_ylim(-5,8)
ax.set_xlim(0,3)

ax.set_xlabel("This is X")
ax.set_ylabel("This is Y")

ax.plot(my_x, my_y1, color='b', marker='None', linestyle='--')
ax.plot(my_x, my_y2, color='r', marker='None', linestyle='-');

Where do they cross? - The sympy solution


In [ ]:
equation_one = 10 * sp.sin(5*x) * sp.exp(-x)
equation_two = 6 - sp.exp(0.75 * x)

In [ ]:
equation_one, equation_two

In [ ]:
my_guess = 0.5

sp.nsolve(equation_one - equation_two, x, my_guess)

In [ ]:
all_guesses = (0.1, 0.5, 2.5)

for i in all_guesses:
    result = sp.nsolve(equation_one - equation_two, x, i)
    print(result)

Your guess has to be (somewhat) close or the solution will not converge:


In [ ]:
my_guess = 200

sp.nsolve(equation_one - equation_two, x, my_guess)

Solve ODE Equations - dsolve


In [ ]:
f = sp.Function('f')

In [ ]:
equation_ode = sp.Derivative(f(x), x, x) + 9*f(x)

equation_ode

In [ ]:
sp.dsolve(equation_ode, f(x))

SymPy can do so much more. It really is magic.

Complete documentation can be found here


$\LaTeX$

Python uses the $\LaTeX$ language to typeset equations.

Most LaTeX commands are prefixed with a "\". For example \pi is the command to produce the lower case Greek letter pi. The characters # $ % & ~ _ ^ \ { } are special characters in LaTeX. If you want to typeset them you need to put a \ in front of them. For example \$ will typeset the symbol $ % - comment. Everything is ignored after a % $ - Math mode. Start and Stop math mode. $\pi$ ^ - Superscript in Math mode. $2^2$ _ - Subscript in Math mode. $2_2$

Use a single set of $ to make your $\LaTeX$ inline and a double set $$ to center

$$ \int \cos(x)\ dx = \sin(x) $$

This code will produce the output:

$$ \int \cos(x)\ dx = \sin(x) $$

Use can use $\LaTeX$ in plots:


In [ ]:
plt.style.use('ggplot')

my_a = np.linspace(0,2*np.pi,100)
my_b = np.sin(5*my_a) * np.exp(-my_a)

In [ ]:
fig,ax = plt.subplots(1,1)
fig.set_size_inches(10,4)

fig.tight_layout()

ax.plot(my_a, my_b, color='r', marker='None', linestyle='-');

ax.set_title("A gratuitous use of $σύμβολον$")
ax.set_xlabel("This is in units of 2$\pi$")
ax.set_ylabel("This is B")

ax.text(2.0, 0.4, '$y\ =\ \sin(5a)\ e^{-a}$', color='green', fontsize=36);

Use can use SymPy to make $\LaTeX$ equations for you!


In [ ]:
a =  1/( ( z + 2 ) * ( z + 1 ) )

print(sp.latex(a))
$$ \frac{1}{\left(z + 1\right) \left(z + 2\right)} $$

In [ ]:
print(sp.latex(sp.Integral(z**2,z)))
$$ \int z^{2}\, dz $$

Astropy can output $\LaTeX$ tables


In [ ]:
from astropy.io import ascii
from astropy.table import QTable

In [ ]:
my_table = QTable.read('./MyData/Zodiac.csv', format='ascii.csv')

In [ ]:
my_table[0:3]

In [ ]:
ascii.write(my_table, format='latex')