Skip to content

Solving Equations

Solving Equations

SymPy's solve() function can be used to solve equations and expressions that contain symbolic math variables.

Equations with one solution

A simple equation that contains one variable like x-4-2 = 0 can be solved using the solve function. When only one value is part of the solution, the solution is in the form of a list.

The code section below demonstrates SymPy's solve() function when an expression is defined with symbolic math variables.

In [1]:
from sympy import symbols, solve

x = symbols('x') expr = x-4-2

sol = solve(expr)

sol

Out[1]:
[6]

To pull the value out of the list, regular list indexing can be used.
In [2]:
num = sol[0]

num

Out[2]:
6

The code section below demonstrates SymPy's solve() function when an equation is defined with symbolic math variables.
In [3]:
from sympy import symbols, Eq, solve

y = symbols('y') eq1 = Eq(y + 3 + 8)

sol = solve(eq1) sol

Out[3]:
[-11]

Equations with two solutions

Quadratic equations, like x^2 - 5x + 6 = 0, have two solutions. SymPy's solve() function can be used to solve an equation with two solutions. When an equation has two solutions, SymPy outputs a list. The elements in the list are the two solutions.

The code section below shows how SymPy's solve() function solves an equation with two solutions.

In [4]:
from sympy import symbols, Eq, solve

y = symbols('x') eq1 = Eq(x*2 -5x + 6)

sol = solve(eq1) sol

Out[4]:
[2, 3]

If you specify the keyword argument dict=True to SymPy's solve() function, the output is still a list, but inside the list is a dictionary that shows which variable was solved for.
In [5]:
from sympy import symbols, Eq, solve

y = symbols('x') eq1 = Eq(x*2 -5x + 6)

sol = solve(eq1, dict=True) sol

Out[5]:
[{x: 2}, {x: 3}]

In [6]:
sol[0]

Out[6]:
{x: 2}

In [7]:
sol[1]

Out[7]:
{x: 3}