SymPy

The SymPy package is useful for symbolic algebra, much like the commercial software Mathematica.

We won't make much use of SymPy during the boot camp, but it is definitely useful to know about for mathematics courses.


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

Symbols and Expressions

We'll define x and y to be sympy symbols, then do some symbolic algebra.


In [2]:
x, y = sp.symbols("x y")

In [3]:
expression = (x+y)**4

In [4]:
expression


Out[4]:
$$\left(x + y\right)^{4}$$

In [5]:
sp.expand(expression)


Out[5]:
$$x^{4} + 4 x^{3} y + 6 x^{2} y^{2} + 4 x y^{3} + y^{4}$$

In [6]:
expression = 8*x**2 + 26*x*y + 15*y**2

In [7]:
expression


Out[7]:
$$8 x^{2} + 26 x y + 15 y^{2}$$

In [8]:
sp.factor(expression)


Out[8]:
$$\left(2 x + 5 y\right) \left(4 x + 3 y\right)$$

In [9]:
expression - 20 *x*y - 14*y**2


Out[9]:
$$8 x^{2} + 6 x y + y^{2}$$

In [10]:
sp.factor(expression - 20*x*y - 14*y**2)


Out[10]:
$$\left(2 x + y\right) \left(4 x + y\right)$$

Lambdify: Making python functions from sympy expressions


In [16]:
expression


Out[16]:
$$8 x^{2} + 26 x y + 15 y^{2}$$

In [12]:
f = sp.lambdify((x,y), expression, 'numpy')

In [17]:
f(3,4)


Out[17]:
$$624$$

In [18]:
8 * 3**2 + 26 * 3 * 4 + 15 * 4**2


Out[18]:
$$624$$

Calculus

You can use sympy to perform symbolic integration or differentiation.


In [26]:
expression = 5*x**2 * sp.sin(3*x**3)

In [27]:
expression


Out[27]:
$$5 x^{2} \sin{\left (3 x^{3} \right )}$$

In [28]:
expression.diff(x)


Out[28]:
$$45 x^{4} \cos{\left (3 x^{3} \right )} + 10 x \sin{\left (3 x^{3} \right )}$$

In [29]:
expression = sp.cos(x)

In [30]:
expression.integrate(x)


Out[30]:
$$\sin{\left (x \right )}$$

In [34]:
expression.integrate((x, 0, sp.pi / 2))


Out[34]:
$$1$$

You can also create unevalated integrals or derivatives. These can later be evaluated with their doit methods.


In [35]:
deriv = sp.Derivative(expression)

In [36]:
deriv


Out[36]:
$$\frac{d}{d x} \cos{\left (x \right )}$$

In [37]:
deriv.doit()


Out[37]:
$$- \sin{\left (x \right )}$$

In [42]:
inte = sp.Integral(expression, (x, 0, sp.pi / 2))

In [43]:
inte


Out[43]:
$$\int_{0}^{\frac{\pi}{2}} \cos{\left (x \right )}\, dx$$

In [44]:
inte.doit()


Out[44]:
$$1$$

In [ ]: