SymPy

In [3]:
import sympy as sp
sp.init_printing()

Symbolic Computation vs Numeric Computations

In [5]:
np.sqrt(8)
Out[5]:
$$2.82842712475$$
In [6]:
sp.sqrt(8)
Out[6]:
$$2 \sqrt{2}$$

Creating symbols, functions and expressions

In [50]:
x, y, z, alpha, beta, gamma = sp.symbols('x y z alpha beta gamma')
x, y, z, alpha, beta, gamma
Out[50]:
$$\left ( x, \quad y, \quad z, \quad \alpha, \quad \beta, \quad \gamma\right )$$
In [15]:
f, g = sp.Function('f'), sp.Function('g')
f(x)
Out[15]:
$$f{\left (x \right )}$$
In [17]:
expr = sp.cos(x) * sp.exp(-x**2)
expr
Out[17]:
$$e^{- x^{2}} \cos{\left (x \right )}$$

Solving equations

In [53]:
equation = sp.Eq(x**2 + 2*alpha*x, -alpha**2)
equation
Out[53]:
$$2 \alpha x + x^{2} = - \alpha^{2}$$
In [55]:
sp.solve(equation, x)
Out[55]:
$$\left [ - \alpha\right ]$$

Differentation

In [18]:
sp.diff(expr)
Out[18]:
$$- 2 x e^{- x^{2}} \cos{\left (x \right )} - e^{- x^{2}} \sin{\left (x \right )}$$
In [16]:
sp.diff(f(x)*g(x))
Out[16]:
$$f{\left (x \right )} \frac{d}{d x} g{\left (x \right )} + g{\left (x \right )} \frac{d}{d x} f{\left (x \right )}$$

Solving differential equations

In [56]:
differential_equation = sp.Eq(f(x).diff(x, x) + alpha * f(x).diff(x) + gamma * f(x), 0)
differential_equation
Out[56]:
$$\alpha \frac{d}{d x} f{\left (x \right )} + \gamma f{\left (x \right )} + \frac{d^{2}}{d x^{2}} f{\left (x \right )} = 0$$
In [58]:
sp.dsolve(differential_equation)
Out[58]:
$$f{\left (x \right )} = C_{1} e^{\frac{x}{2} \left(- \alpha - \sqrt{\alpha^{2} - 4 \gamma}\right)} + C_{2} e^{\frac{x}{2} \left(- \alpha + \sqrt{\alpha^{2} - 4 \gamma}\right)}$$

Integrate

In [41]:
sp.integrate(f(x))
Out[41]:
$$\int f{\left (x \right )}\, dx$$
In [60]:
sp.integrate(sp.sin(alpha * x + beta), x)
Out[60]:
$$\begin{cases} x \sin{\left (\beta \right )} & \text{for}\: \alpha = 0 \\- \frac{1}{\alpha} \cos{\left (\alpha x + \beta \right )} & \text{otherwise} \end{cases}$$

Limits

In [61]:
expr = sp.Limit(sp.sin(alpha * x)/x, x, 0)
expr
Out[61]:
$$\lim_{x \to 0^+}\left(\frac{1}{x} \sin{\left (\alpha x \right )}\right)$$
In [62]:
expr.doit()
Out[62]:
$$\alpha$$

Series expansion

In [47]:
sp.sin(x).series(x, 0, 10)
Out[47]:
$$x - \frac{x^{3}}{6} + \frac{x^{5}}{120} - \frac{x^{7}}{5040} + \frac{x^{9}}{362880} + \mathcal{O}\left(x^{10}\right)$$

Visualization

2d plotting

In [70]:
%matplotlib inline
sp.plotting.plot(sp.sin(x), (x, -2 * sp.pi, 2 * sp.pi))
Out[70]:
<sympy.plotting.plot.Plot at 0x7ff5396846d8>
In [80]:
sp.plotting.plot_parametric(x*sp.sin(x)/sp.pi, -x*sp.cos(x)/sp.pi, (x, 0, 10 * sp.pi))
Out[80]:
<sympy.plotting.plot.Plot at 0x7ff539739f28>

3d Plotting

In [71]:
sp.plotting.plot3d(sp.sin(x)*sp.cos(y), (x, -sp.pi, sp.pi), (y, -sp.pi, sp.pi))
Out[71]:
<sympy.plotting.plot.Plot at 0x7ff5396d7cc0>
In [73]:
sp.plotting.plot3d_parametric_line(sp.sin(x), sp.cos(x), x, (x, -2*sp.pi, 2*sp.pi))
Out[73]:
<sympy.plotting.plot.Plot at 0x7ff53978cba8>