Python SymPy – Find roots of an equation

In this post we will be creating a Python script that will find the roots of a given equation, this is the solution or values that make an equation true. To achieve this we will be utilizing the SymPy library in Python which is a library for symbolic mathematics.

In the examples below we will make use of the ‘roots()’ function which finds the solution or values that satisfy a polynomial equation. See the snippet of Python code below where we find the roots of the following equation.

x2 – 4

from sympy import *

x = Symbol('x')

expr = x**2 - 4

print(roots(expr))

The above would return ‘{-2: 1, 2: 1}‘ as the solution, meaning x= -2 and x= 2. See another example below where we solve the following equation.

x2 – 7x + 11

from sympy import *

x = Symbol('x')

expr = x**2-7*x+11

print(roots(expr))

The above would return ‘{7/2 – sqrt(5)/2: 1, sqrt(5)/2 + 7/2: 1}‘ as the solution.

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply