# Symbolic mathematics with Sympy

[Sympy](http://www.sympy.org/en/index.html) is described as a:

> "... Python library for symbolic mathematics."

This means it can be used to:

- Manipulate symbolic expressions;
- Solve symbolic equations;
- Carry out symbolic Calculus;
- Plot symbolic function.

It has other capabilities that we will not go in to in this handbook. But you can read more about it here: http://www.sympy.org/en/index.html

## Manipulating symbolic expressions

Before we can start using the library to manipulate expressions, we need to import it.


```python
import sympy as sym
```

The above imports the library and gives us access to it's commands using the shortand `sym` which is conventially used.

If we wanted to get Python to check that $x - x = 0$ we would get an error if we did not tell Python what $x$ was:


```python
x - x
```

This is where Sympy comes in, we can tell Python to create $x$ as a symbolic variable:


```python
x = sym.symbols('x')
```

Now we can calculate $x - x$:


```python
x - x
```




    0



We can create and manipulate expressions in Sympy. Let us for example verify:

$$(a + b) ^ 2 = a ^ 2 + 2ab + b ^2$$

First, we create the symbolic variables $a, b$:


```python
a, b = sym.symbols('a, b')
```

Now let's create our expression:


```python
expr = (a + b) ** 2 
expr
```




    (a + b)**2



**Note** we can get Sympy to use LaTeX so that the output looks nice in a notebook:


```python
sym.init_printing()
```


```python
expr
```

Let us expand our expression:


```python
expr.expand()
```

Note that we can also get Sympy to produce the LaTeX code for future use:


```python
sym.latex(expr.expand())
```




    'a^{2} + 2 a b + b^{2}'



---
**EXERCISE** Use Sympy to verify the following expressions:

- $(a - b) ^ 2 = a ^ 2 - 2 a b + b^2$
- $a ^ 2 - b ^ 2 = (a - b) (a + b)$ (instead of using `expand`, try `factor`)

## Solving symbolic equations

We can use Sympy to solve symbolic expression. For example let's find the solution in $x$ of the quadratic equation:

$$a x ^ 2 + b x + c = 0$$


```python
# We only really need to define `c` but doing them all again.
a, b, c, x = sym.symbols('a, b, c, x')  
```

The Sympy command for solving equations is `solveset`. The first argument is an expression for which the root will be found. The second argument is the value that we are solving for.


```python
sym.solveset(a * x ** 2 + b * x + c, x)
```

---
**EXERCISE** Use Sympy to find the solutions to the generic cubic equation:

$$a x ^ 3 + b x ^ 2 + c  x + d = 0$$

---

It is possible to pass more arguments to `solveset` for example to constrain the solution space. Let us see what the solution of the following is in $\mathbb{R}$:

$$x^2=-1$$


```python
sym.solveset(x ** 2 + 1, x, domain=sym.S.Reals)
```

---
**EXERCISE** Use Sympy to find the solutions to the following equations:

- $x ^ 2 == 2$ in $\mathbb{N}$;
- $x ^ 3 + 2 x = 0$ in $\mathbb{R}$.

---

## Symbolic calculus

We can use Sympy to compute limits. Let us calculate:

$$\lim_{x\to 0^+}\frac{1}{x}$$


```python
sym.limit(1/x, x, 0, dir="+")
```

---
**EXERCISE** Compute the following limits:

1. $\lim_{x\to 0^-}\frac{1}{x}$
2.  $\lim_{x\to 0}\frac{1}{x^2}$

---

We can use also Sympy to differentiate and integrate. Let us experiment with differentiating the following expression:

$$x ^ 2 - \cos(x)$$


```python
sym.diff(x ** 2 - sym.cos(x), x)
```

Similarly we can integrate:


```python
sym.integrate(x ** 2 - sym.cos(x), x)
```

We can also carry out definite integrals:


```python
sym.integrate(x ** 2 - sym.cos(x), (x, 0, 5))
```

---

**EXERCISE** Use Sympy to calculate the following:

1. $\frac{d\sin(x ^2)}{dx}$
2. $\frac{d(x ^2 + xy - \ln(y))}{dy}$
3. $\int e^x \cos(x)\;dx$
4. $\int_0^5 e^{2x}\;dx$

## Plotting with Sympy

Finally Sympy can be used to plot functions. Note that this makes use of another Python library called [matplotlib](http://matplotlib.org/). Whilst Sympy allows us to not directly need to make use of matplotlib it could be worth learning to use as it's a very powerful and versatile library.

Before plotting in Jupyter we need to run a command to tell it to display the plots directly in the notebook:


```python
%matplotlib inline
```

Let us plot $x^2$:


```python
expr = x ** 2
p = sym.plot(expr);
```

We can directly save that plot to a file if we wish to:


```python
p.save("x_squared.pdf");
```

---
**EXERCISE** Plot the following functions:

- $y=x + cos(x)$
- $y=x ^ 2 - e^x$ (you might find `ylim` helpful as an argument)

Experiment with saving your plots to a file.

---

## Summary

This section has discussed using Sympy to:

- Manipulate symbolic expressions;
- Calculate limits, derivates and integrals;
- Plot a symbolic expression.
    
This just touches the surface of what Sympy can do.

Let us move on to using [Numpy](02 - Linear algebra with Numpy.ipynb) to do Linear Algebra.

727ee86219297137131767a233d6483865705b16
ipynb
Jupyter Notebook
nbs/01-Symbolic-mathematics-with-Sympy.ipynb
dianetam523/Python-Mathematics-Handbook
04036b58dc82943c9ac577abe74c1a2b387e40ce
MIT
nbs/01-Symbolic-mathematics-with-Sympy.ipynb
dianetam523/Python-Mathematics-Handbook
04036b58dc82943c9ac577abe74c1a2b387e40ce
MIT
nbs/01-Symbolic-mathematics-with-Sympy.ipynb
dianetam523/Python-Mathematics-Handbook
04036b58dc82943c9ac577abe74c1a2b387e40ce
MIT
Qwen/Qwen-72B
1. YES
2. YES