---
title: Sympy
file_title: Sympy
---
### Solving Algebraic Roots¶

### Conclusion¶

`SymPy`

is a symbolic mathematics library built on the Python programming language.

In this post we'll look at how to use some of the basic functions of the library.

In [1]:

```
import sympy as sy
```

The equation that we want to solve is in the form of \begin{equation} a x^2 + bx + c = 0 \end{equation}

Let's solve for the roots of the quadratic equation. First we have to define the relevant variables as sympy symbols. We can accomplish this in one line by using the `symbols`

function, providing a list of variables, and setting them to the associated variables that we want to use. The order does matter [^1].

In [2]:

```
a, b, c, x = sy.symbols('a, b, c, x')
```

Next, let's define the quadratic equation as a `sympy`

equation using the `Eq`

function. Note that the equation is assumed to be equal to zero.

In [3]:

```
eq = sy.Eq(a*x**2 + b*x + c)
```

Let's make sure that our equation looks right by printing it:

In [4]:

```
print(eq)
```

This is pretty ugly. Luckily, we can print a much better version using tools built into `sympy`

.

In [5]:

```
sy.init_printing(use_latex='mathjax')
eq
```

Out[5]:

We can even print out the $\LaTeX{}$ used to display the equation we can be copied and pated into $\LaTeX{}$ documents.

In [6]:

```
sy.print_latex(eq)
```

Now, let's go ahead and solve the equation for $x$. All we need to do is call the `sympy.solve`

function with the equation and the variable we want to find.

In [7]:

```
solutions = sy.solve(eq, x)
solutions
```

Out[7]:

The function returned a list of solutions. The quadratic equation has two roots (which should come as no suprise). Using typical python syntax we can extract the first solution:

In [8]:

```
solutions[0]
```

Out[8]:

We can even substitute in values for the constant coefficients using the `subs`

method on the first solution:

In [9]:

```
solutions[0].subs({a:1,b:2,c:-1})
```

Out[9]:

`SymPy`

is a great stand-alone symbolic computing library. It has many features, and its integrations with Jupyter notebooks makes it great for interactive computational mathematics. Because Python is a free, open source langauge it can be extended for uses such as symbolic computations and retain the rich programming features that are built into the core of the language.