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 SymPy’s 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.

from sympy import symbols, solve

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

sol = solve(expr)

sol
[6]

To pull the value out of the solution list sol, regular list indexing can be used.

num = sol[0]

num
\[\displaystyle 6\]

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

from sympy import symbols, Eq, solve

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

sol = solve(eq1)
sol
/Users/phil/a50037/envs/june22/lib/python3.7/site-packages/sympy/core/relational.py:490: SymPyDeprecationWarning: 

Eq(expr) with rhs default to 0 has been deprecated since SymPy 1.5.
Use Eq(expr, 0) instead. See
https://github.com/sympy/sympy/issues/16587 for more info.

  deprecated_since_version="1.5"
[-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’s solve() function outputs a list. The elements in the list are the two solutions.

The code section below shows how an equation with two solutions is solved with SymPy’s solve() function.

from sympy import symbols, Eq, solve

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

sol = solve(eq1)
sol
[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.

from sympy import symbols, Eq, solve

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

sol = solve(eq1, dict=True)
sol
[{x: 2}, {x: 3}]
sol[0]
{x: 2}
sol[1]
{x: 3}