# My SymPy Cheat-Sheet¶

## Preliminaries¶

First things first. Load in SymPy, the engine to do symbolic calculations, and optionally IPython "display", which lets you render LaTeX equations in IPython notebooks using MathJax, after you execute the "init-(underscore)-printing" command.
In [2]:
from sympy import *
from IPython.display import display
init_printing(use_latex='mathjax')
%matplotlib inline

## Defining Variables and Scoping¶

Symbolic variables need to be defined before they are used. One can also define the type and scope of the variable. This might allow the SymPy engine to apply additional simplifications.
In [3]:
x, y, z = symbols('x, y, z')
m = symbols('m', integer=True)
f = symbols('f', cls=Function)
a, b = symbols('a, b', real=True, positive=True)

## Algebra¶

In [4]:
expr1 = x + 1
In [5]:
print expr1, type(expr1)
One can plot the expression to see what it looks like
In [6]:
plot(expr1,(x,0,3),title='simple plot', xlabel='x', ylabel='x+1')
Out[6]:
<sympy.plotting.plot.Plot at 0xb06394ac>
Note that, in general, the python variable "x" is different from the SymPy variable "x". You can use the "subs" command to do substitutions.
In [9]:
expr = x+y**2*sin(x); print expr.subs(x,1)
y**2*sin(1) + 1
You can substitute multiple variables at once
In [11]:
print expr.subs({x:1, y:2})
1 + 4*sin(1)
And in case, you need to do non-sequential substitution:
In [13]:
print expr.subs([(x,y), (y,x)], simultaneous=True)
x**2*sin(y) + y

## Polynomials¶

One can take any polynomial, and write it out in the canonical expanded form using "expand", and back factor them using the command "factor". The iPython command "display" lets you typeset using MathJax.
In [9]:
expandedForm = expand((x+2)*(x-3)); display(expandedForm)
$$x^{2} - x - 6$$
In [10]:
display(factor(expandedForm))
$$\left(x - 3\right) \left(x + 2\right)$$
In [11]:
display(factor(expandedForm + 7 - x))
$$\left(x - 1\right)^{2}$$
If you have an expression with multiple variables, you can "collect" or rewrite it in terms of a particular variable.
In [12]:
expr = x*y + x - 3 + 2*x**2 - z*x**2 + x**3; display(expr)
$$x^{3} - x^{2} z + 2 x^{2} + x y + x - 3$$
In [13]:
collected_expr = collect(expr, x); display(collected_expr)
$$x^{3} + x^{2} \left(- z + 2\right) + x \left(y + 1\right) - 3$$

## Trignometry¶

You can use trig identities (sum and double angle identities) to expand out arguments, or carry out simplifications.
In [14]:
display(expand_trig(sin(x + y))) # uses sum/double angle utilities
$$\sin{\left (x \right )} \cos{\left (y \right )} + \sin{\left (y \right )} \cos{\left (x \right )}$$
In [15]:
display(trigsimp(sin(x)**4 - 2*cos(x)**2*sin(x)**2 + cos(x)**4))  # applies trig identities
$$\frac{1}{2} \cos{\left (4 x \right )} + \frac{1}{2}$$

## Manipulation¶

The multi-purpose simplification command is "simplify"
In [16]:
a = (x + 1)**2
b = x**2 + 2*x + 1
display(simplify(a - b))
$$0$$
In [17]:
c = x**2 - 2*x + 1
display(simplify(a - c))
$$4 x$$

## Calculus¶

These are often extremely handy time-savers.

### Derivatives¶

The generic command is "diff", you can take derivatives of different order, and with respect to different variables
In [18]:
f = (x-1)**m * exp(x); display(f)
$$\left(x - 1\right)^{m} e^{x}$$
Usual first ordered derivative
In [19]:
diff(f,x)
Out[19]:
$$\frac{m \left(x - 1\right)^{m} e^{x}}{x - 1} + \left(x - 1\right)^{m} e^{x}$$
Second and higher order order derivatives
In [20]:
diff(f,x,2)
Out[20]:
$$\left(x - 1\right)^{m} \left(\frac{m^{2}}{\left(x - 1\right)^{2}} + \frac{2 m}{x - 1} - \frac{m}{\left(x - 1\right)^{2}} + 1\right) e^{x}$$

Perhaps you want to write out an expression for Newton's rule, where $$x_{n+1} = x_{n} - \frac{f(x_n)}{f'(x_n)}$$

In [21]:
g = simplify(x - f/diff(f,x)); display(g)
$$\frac{m x + x^{2} - 2 x + 1}{m + x - 1}$$
One can generate LaTeX output to embed in a document easily;
In [22]:
latex(diff(f, x))
Out[22]:
'\\frac{m \\left(x - 1\\right)^{m} e^{x}}{x - 1} + \\left(x - 1\\right)^{m} e^{x}'

### Integrals¶

The generic integration command is integrate. Note that "infinity" is represented as "oo". Here we try the integral $I = \int_{-\infty}^{\infty} \sin x^2 dx$

In [23]:
intg = integrate(sin(x**2), (x, -oo, oo)); display(intg)
$$\frac{\sqrt{2} \sqrt{\pi}}{2}$$

Or perhaps another interesting one $\int_0^1 x^{x} dx$

In [24]:
intg = integrate(x**x, (x, 0, 1)); display(intg); plot(x**x, (x,0,1))
$$\int_{0}^{1} x^{x}\, dx$$
Out[24]:
<sympy.plotting.plot.Plot at 0xb03ca6cc>
It couldn't find a closed for expression for the integral. One can evaluate the integral numerically using "N" or "evalf" modules, and optionally request the number of significant digits.
In [25]:
print intg.evalf(10) # Like N[expr,10] in Mathematica
print N(intg, 30)
0.7834305107
0.783430510712134407059264386527

### Taylor Series and Series Summation¶

"series", lets you carry out a taylor series expansion around a point up to a specified order. The "O" notation can be suppressed if required.
In [26]:
expr = exp(sin(x))
display(expr.series(x, 0, 4))
$$1 + x + \frac{x^{2}}{2} + \mathcal{O}\left(x^{4}\right)$$
In [27]:
display(expr.series(x, 0, 4).removeO())
$$\frac{x^{2}}{2} + x + 1$$
One can also do Taylor series of two variables using a one-liner
In [28]:
expr = sin(x*cos(y)); display(expr)
$$\sin{\left (x \cos{\left (y \right )} \right )}$$
In [29]:
expr.series(x, 0, 3).removeO().series(y, 0, 3).removeO()
Out[29]:
$$- \frac{x y^{2}}{2} + x$$
Another handy command is summation
In [30]:
j = symbols('j',integer=True, positive=True)
expr = summation(j**2, (j,1,m)); display(expr)
$$\frac{m^{3}}{3} + \frac{m^{2}}{2} + \frac{m}{6}$$

## Solve Equations¶

In [31]:
expr = x**2 + 3*x + 2
print solve(expr)
[-2, -1]
In [32]:
expr1 = x + y - 2
expr2 = x - y - 4
print solve([expr1, expr2],(x,y))
{x: 3, y: -1}

## Units¶

In [33]:
from sympy.physics import units as u
In [34]:
print u.watt
kg*m**2/s**3
In [35]:
mph = u.mile / u.hour
mps = u.meter / u.second
In [36]:
print N(mps/mph), "mph = 1 mps"
2.23693629205440 mph = 1 mps