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: aFiniteSet, anInterval,EmptySet, an infiniteImageSetfor periodic solutions likesin(x) = 0, or aConditionSetwhen it cannot solve. Thedomainargument matters:x**2 + 1 = 0has no real solutions but two complex ones.solve(eq, x)is older and returns a list (or a list of dicts for systems withdict=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.739085133215161Remember
- 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.