Solving equations

SymPy · Essentials · 12 min

Solving for an unknown is the most common reason people reach for a CAS.

An equation is an Eq(lhs, rhs) object, because = is assignment and == is structural comparison. Solvers also accept a plain expression, which they treat as expr = 0.

SymPy has two main solvers:

  • solveset(eq, x, domain=S.Reals) is the modern interface. It returns a set: a FiniteSet, an Interval, EmptySet, an infinite ImageSet for periodic solutions like sin(x) = 0, or a ConditionSet when it cannot solve. The domain argument matters: x**2 + 1 = 0 has no real solutions but two complex ones.
  • solve(eq, x) is older and returns a list (or a list of dicts for systems with dict=True). It is convenient for quick work and solves for one variable in terms of others nicely.

For systems, linsolve([eq1, eq2], [x, y]) solves linear systems, nonlinsolve handles polynomial systems, and solve([eq1, eq2], [x, y], dict=True) works for many cases.

If an equation has no closed-form solution, such as cos(x) = x, use the numeric nsolve(expr, x, guess), which finds one root near the guess.

Always check what kind of object you got back before indexing into it: an ImageSet or ConditionSet cannot be iterated like a list.

Example

from sympy import symbols, Eq, solveset, solve, linsolve, nsolve, S, sin, cos

x, y = symbols("x y")
print(solveset(Eq(x**2, 4), x))              # {-2, 2}
print(solveset(x**2 + 1, x, domain=S.Reals)) # EmptySet
print(solveset(x**2 + 1, x))                 # {-I, I}
print(solveset(sin(x), x, domain=S.Reals))
# Union(ImageSet(Lambda(_n, 2*_n*pi), Integers), ImageSet(Lambda(_n, 2*_n*pi + pi), Integers))

print(solve(x**2 - y, x))                    # [-sqrt(y), sqrt(y)]
print(linsolve([x + y - 3, x - y - 1], [x, y]))  # {(2, 1)}
print(solve([x + y - 3, x - y - 1], [x, y], dict=True))  # [{x: 2, y: 1}]
print(nsolve(cos(x) - x, x, 1))              # 0.739085133215161

Remember

  • Write equations as Eq(lhs, rhs) or as an expression equal to zero
  • solveset returns sets and respects domain; solve returns lists
  • Use linsolve for linear systems and nsolve when there is no closed form

Watch out for

  • Indexing the result of solveset like a list: it may be an infinite ImageSet or a ConditionSet.

Check yourself

  1. solveset(x**2 + 1, x, domain=S.Reals) returns:

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.sympy.org/latest/tutorials/intro-tutorial/solvers.html