ZetCode

Python SymPy

last modified November 19, 2026 Python 3.15

In this article we show how to do symbolic mathematics in Python with the SymPy library.

SymPy

SymPy is a Python library for symbolic mathematics, a computer algebra system written in pure Python. Unlike numerical libraries, which work with floating-point approximations, SymPy manipulates mathematical expressions exactly: sqrt(8) stays 2*sqrt(2) and 1/3 stays a fraction. It can simplify expressions, solve equations, differentiate and integrate, and compute limits and series.

SymPy depends only on the mpmath library for arbitrary-precision arithmetic. Plotting needs Matplotlib. The examples were run with SymPy 1.14.

$ pip install sympy matplotlib

Symbols and expressions

Variables in SymPy expressions are symbols. They must be created before use, usually with the symbols function. An arithmetic operation on a symbol does not compute a value; it builds an expression.

first_symbols.py
from sympy import symbols

x, y = symbols('x y')

expr = 2*x + 3*y
print(expr)
print(expr + x)
print(expr * x)
print(type(expr))

e2 = x*y + y*x - 4*x + 4*x + 3*(x + y)
print(e2)

The symbols function takes names separated by spaces and returns one Symbol per name. The expression 2*x + 3*y is an object of the Add class. SymPy brings every expression into a canonical form: like terms are collected (x*y + y*x becomes 2*x*y, -4*x + 4*x disappears), but products such as x*(2*x + 3*y) are not multiplied out automatically. Only cheap transformations are done; the expensive ones are left to functions such as expand and simplify.

$ python first_symbols.py
2*x + 3*y
3*x + 3*y
x*(2*x + 3*y)
<class 'sympy.core.add.Add'>
2*x*y + 3*x + 3*y

Exact numbers

SymPy keeps rational numbers and roots exact. A Rational is a fraction of two integers.

exact_numbers.py
from sympy import Rational, sqrt, Integer, S

r = Rational(1, 10)
print(r + r + r)
print(0.1 + 0.1 + 0.1)

print(Rational(1/10))
print(S('1/10'))

print(Integer(1) / 3)
print(1 / 3)

print(sqrt(8))
print(sqrt(2) * sqrt(2))
print(sqrt(2) ** 3)

Adding three exact tenths gives 3/10, while the float sum is off in the last digit. Note the pitfall in Rational(1/10): Python computes 1/10 as a float first, so SymPy receives the binary approximation of 0.1 and converts it exactly. Use two integers or a string, S('1/10'), instead. Dividing two Python integers gives a float; dividing a SymPy Integer keeps the fraction. Roots are simplified, so sqrt(8) is 2*sqrt(2).

$ python exact_numbers.py
3/10
0.30000000000000004
3602879701896397/36028797018963968
1/10
1/3
0.3333333333333333
2*sqrt(2)
2
2*sqrt(2)

Numerical evaluation

The evalf method, or the N function, evaluates an expression to a floating-point number with a chosen number of significant digits.

evaluating.py
from sympy import pi, E, sqrt, Rational, N

print(pi)
print(pi.evalf())
print(pi.evalf(40))
print(N(sqrt(2), 25))
print(E.evalf(15))

val = Rational(1, 3) + sqrt(5)
print(val)
print(val.evalf(8))
print(float(val))

Constants such as pi and E are symbolic. Without an argument evalf gives 15 significant digits; with an argument it can give any number of digits, because SymPy uses mpmath for arbitrary-precision arithmetic. The float function converts the expression to an ordinary Python float.

$ python evaluating.py
pi
3.14159265358979
3.141592653589793238462643383279502884197
1.414213562373095048801689
2.71828182845905
1/3 + sqrt(5)
2.5694013
2.569401310833123

Substitution

The subs method replaces symbols with numbers or with other expressions.

substitution.py
from sympy import symbols, Rational

x, y = symbols('x y')
expr = x**2 + 3*x*y - y

print(expr.subs(x, 2))
print(expr.subs({x: 2, y: 5}))
print(expr.subs({x: Rational(1, 2), y: 1}))
print(expr.subs(y, x + 1))
print(expr.evalf(subs={x: 1.5, y: 2}))
print(expr)

We can substitute one symbol, or several at once with a dictionary. A substituted value may be another expression, as in y replaced by x + 1. The evalf method accepts a subs dictionary and returns a float. Expressions are immutable; subs returns a new expression and the original stays unchanged.

$ python substitution.py
5*y + 4
29
3/4
x**2 + 3*x*(x + 1) - x - 1
9.25000000000000
x**2 + 3*x*y - y

Pretty printing

The print function shows an expression in Python syntax. The pprint function draws it in two dimensions and the latex function converts it to LaTeX.

pretty.py
from sympy import symbols, sqrt, exp, Rational, pprint, latex

x = symbols('x')
expr = sqrt(x**2 + 1) / (x - 1) + exp(-x) + Rational(3, 4)

print(expr)
pprint(expr)
pprint(expr, use_unicode=False)
print(latex(expr))

By default pprint uses Unicode box-drawing characters; with use_unicode=False it uses only ASCII. The LaTeX string can be pasted into a document. In Jupyter notebooks, the init_printing function renders expressions as typeset formulas.

$ python pretty.py
3/4 + exp(-x) + sqrt(x**2 + 1)/(x - 1)
             ________
            ╱  2     
3    -x   ╲╱  x  + 1 
─ + ℯ   + ───────────
4            x - 1   
             ________
            /  2     
3    -x   \/  x  + 1 
- + e   + -----------
4            x - 1   
\frac{3}{4} + e^{- x} + \frac{\sqrt{x^{2} + 1}}{x - 1}

Expanding and factoring

The expand function multiplies out products and powers; factor does the opposite and writes a polynomial as a product of irreducible factors.

expand_factor.py
from sympy import symbols, expand, factor, pprint, I

x, y = symbols('x y')

e1 = (x + 1)**2 * (x - y)
pprint(e1)
pprint(expand(e1))

e2 = x**3 - 6*x**2 + 11*x - 6
pprint(factor(e2))

e3 = x**4 - 1
print(factor(e3))
print(factor(e3, extension=I))

By default factor works over the rational numbers, so x**2 + 1 stays as it is. With extension=I, the imaginary unit is allowed in the coefficients and the factor splits further.

$ python expand_factor.py
       2        
(x + 1) ⋅(x - y)
 3    2        2                
x  - x ⋅y + 2⋅x  - 2⋅x⋅y + x - y
(x - 3)⋅(x - 2)⋅(x - 1)
(x - 1)*(x + 1)*(x**2 + 1)
(x - 1)*(x + 1)*(x - I)*(x + I)

Simplification

The simplify function tries various transformations and returns the shortest result. Specialized functions such as trigsimp and cancel do one kind of simplification and are faster and more predictable.

simplify_exprs.py
from sympy import symbols, sin, cos, exp, log, simplify, trigsimp, cancel

x = symbols('x')

print(simplify(sin(x)**2 + cos(x)**2))
print(simplify(sin(x) / cos(x)))
print(trigsimp(2*sin(x)*cos(x)))
print(cancel((x**2 - 1) / (x - 1)))
print(simplify(exp(log(x))))
print(simplify(log(exp(x))))

The cancel function cancels common factors of a rational function. The last two lines show that simplify is careful: exp(log(x)) is x, but log(exp(x)) is not simplified, because it equals x only for real x, and a plain symbol may be complex. The next sections show how to tell SymPy more about a symbol.

$ python simplify_exprs.py
1
tan(x)
sin(2*x)
x + 1
x
log(exp(x))

Comparing expressions

The == operator tests whether two expressions are structurally identical, not whether they are mathematically equal.

compare_exprs.py
from sympy import symbols, sin, cos, simplify

x = symbols('x')

a = cos(x)**2 - sin(x)**2
b = cos(2*x)

print(a == b)
print(a.equals(b))
print(simplify(a - b) == 0)

c = (x + 1)**2
d = x**2 + 2*x + 1
print(c == d)
print(c.expand() == d)

cos(x)**2 - sin(x)**2 and cos(2*x) are equal functions but different expression trees, so == returns False. The equals method tests mathematical equality (it simplifies the difference and, if needed, evaluates it at random points). A reliable alternative is to check that the simplified difference is zero. Expanding one side is enough for polynomials.

$ python compare_exprs.py
False
True
True
False
True

Assumptions

Symbols are complex numbers unless told otherwise. Assumptions such as positive=True or integer=True allow simplifications that are not valid in general.

assumptions.py
from sympy import symbols, Symbol, sqrt, simplify, log

x = symbols('x')
print(sqrt(x**2))

p = Symbol('p', positive=True)
print(sqrt(p**2))
print(p.is_positive, x.is_positive)

n = Symbol('n', integer=True)
print((-1)**(2*n))

a, b = symbols('a b', positive=True)
print(simplify(log(a*b) - log(a) - log(b)))
print(simplify(log(x*x) - 2*log(x)))

For a general x, sqrt(x**2) is not x (it is -x for negative x), so it is left alone. For a positive symbol it simplifies to p. The is_positive attribute is None when the answer is unknown. For an integer n, (-1)**(2*n) is 1. The logarithm rule log(a*b) = log(a) + log(b) holds for positive numbers only, so the difference simplifies to zero for a and b but not for x.

$ python assumptions.py
sqrt(x**2)
p
True None
1
0
-2*log(x) + log(x**2)

Solving equations

The solve function returns a list of solutions; solveset returns a mathematical set and lets us choose the domain.

solving.py
from sympy import symbols, Eq, solve, solveset, S

x = symbols('x')

print(solve(x**2 - x, x))
print(solve(Eq(2*x + 1, 7), x))

print(solve(x**2 + 1, x))
print(solveset(x**2 + 1, x, domain=S.Reals))
print(solveset(x**2 - 2, x))

print(solveset(x**2 - 1, x, domain=S.Naturals))
print(solveset(x > 3, x, domain=S.Reals))

An expression passed to solve is set equal to zero, so x**2 - x means x² = x. An equation with two sides is written with Eq; the = and == operators cannot be used for that. The equation x² + 1 = 0 has two complex solutions, but no real one, so solveset with the real domain returns the empty set. The default domain of solveset is the complex numbers. It can also restrict solutions to natural numbers and solve inequalities, which gives an interval.

$ python solving.py
[0, 1]
[3]
[-I, I]
EmptySet
{-sqrt(2), sqrt(2)}
{1}
Interval.open(3, oo)

Systems of equations

A system of equations is passed as a list. The linsolve function is specialized for linear systems and nonlinsolve for nonlinear ones.

equation_systems.py
from sympy import symbols, Eq, solve, linsolve, nonlinsolve

x, y, z = symbols('x y z')

eqs = [Eq(x + y, 10), Eq(2*x - y, 2)]
print(solve(eqs, [x, y]))

sol = linsolve([x + y + z - 6, x - y + z - 2, 2*x + y - z - 1], [x, y, z])
print(sol)

print(linsolve([x + y - 1, 2*x + 2*y - 2], [x, y]))
print(linsolve([x + y - 1, x + y - 2], [x, y]))

print(nonlinsolve([x**2 + y**2 - 25, x - y - 1], [x, y]))

For a system, solve returns a dictionary. The linsolve function returns a set of tuples in the order of the given symbols. When the equations are dependent, the solution is a family expressed by the free symbol, here (1 - y, y); when they contradict each other, the result is the empty set. The circle x² + y² = 25 intersects the line x - y = 1 in two points.

$ python equation_systems.py
{x: 4, y: 6}
{(1, 2, 3)}
{(1 - y, y)}
EmptySet
{(-3, -4), (4, 3)}

Derivatives

The diff function computes derivatives. The Derivative class creates an unevaluated derivative.

derivatives.py
from sympy import symbols, diff, sin, exp, log, Derivative, pprint

x, y = symbols('x y')

print(diff(x**3 + 2*x, x))
print(diff(sin(x) * exp(x), x))
print(diff(log(x), x, 2))
print(diff(x**2 * y**3, x, y))

d = Derivative(x**4, x)
pprint(d)
print(d.doit())

SymPy applies the product rule to sin(x) * exp(x). A number after the variable gives the order of the derivative, so diff(log(x), x, 2) is the second derivative. Several variables give a mixed partial derivative. The unevaluated Derivative can be printed as a formula and computed later with doit.

$ python derivatives.py
3*x**2 + 2
exp(x)*sin(x) + exp(x)*cos(x)
-1/x**2
6*x*y**2
d ⎛ 4⎞
──⎝x ⎠
dx    
4*x**3

Local extrema

Derivatives and solve together find the local extrema of a function: the first derivative is zero at a critical point, and the sign of the second derivative tells whether it is a minimum or a maximum.

extrema.py
from sympy import symbols, diff, solve

x = symbols('x')
f = x**3 - 6*x**2 + 9*x + 1

df = diff(f, x)
d2f = diff(f, x, 2)
print(f"f'(x) = {df}")
print(f"f''(x) = {d2f}")

for c in solve(df, x):
    curv = d2f.subs(x, c)
    kind = 'minimum' if curv > 0 else 'maximum' if curv < 0 else 'unknown'
    print(f'x = {c}: f(x) = {f.subs(x, c)}, local {kind}')

The derivative 3*x**2 - 12*x + 9 is zero at 1 and 3. The second derivative is negative at 1 (a maximum) and positive at 3 (a minimum). The results are exact integers, because the whole computation is symbolic.

$ python extrema.py
f'(x) = 3*x**2 - 12*x + 9
f''(x) = 6*(x - 2)
x = 1: f(x) = 5, local maximum
x = 3: f(x) = 1, local minimum

Integrals

The integrate function computes indefinite integrals and, with a tuple of the variable and limits, definite integrals.

integrals.py
from sympy import symbols, integrate, sin, exp, oo, sqrt, pi, Integral, pprint

x = symbols('x')

print(integrate(x**2, x))
print(integrate(sin(x) * exp(x), x))
print(integrate(x**2, (x, 0, 3)))
print(integrate(exp(-x**2), (x, -oo, oo)))

i = Integral(sqrt(1 - x**2), (x, -1, 1))
pprint(i)
print(i.doit())
print(i.doit() == pi / 2)

SymPy does not add the constant of integration to indefinite integrals. The limits can be infinite; oo (two lowercase letters o) is infinity, and the Gaussian integral gives the square root of pi. The integral of sqrt(1 - x**2) from -1 to 1 is the area of a half unit circle, pi/2.

$ python integrals.py
x**3/3
exp(x)*sin(x)/2 - exp(x)*cos(x)/2
9
sqrt(pi)
1                
⌠                
⎮     ________   
⎮    ╱      2    
⎮  ╲╱  1 - x   dx
⌡                
-1               
pi/2
True

Limits

The limit function computes the limit of an expression as a variable approaches a point.

limits.py
from sympy import symbols, limit, sin, oo, Limit, exp

x, n = symbols('x n')

print(limit(sin(x) / x, x, 0))
print(limit(1 / x, x, oo))

print(limit(1 / x, x, 0))
print(limit(1 / x, x, 0, '-'))
print(limit(1 / x, x, 0, '+-'))

print(limit((1 + 1/n)**n, n, oo))
print(Limit(exp(-x), x, oo).doit())

The limit of 1/x at 0 depends on the direction. SymPy computes the limit from the right by default ('+'), so the result is infinity; from the left ('-') it is minus infinity. With '+-', both sides are considered; they differ, and SymPy returns zoo, the complex infinity. The limit of (1 + 1/n)**n is Euler's number E.

$ python limits.py
1
0
oo
-oo
zoo
E
0

Series and sums

The series function computes a Taylor series of a function. The summation function computes finite and infinite sums.

series_sums.py
from sympy import symbols, series, sin, exp, summation, oo, factorial, Sum, pprint

x, k, n = symbols('x k n', integer=True)
t = symbols('t')

print(series(sin(t), t, 0, 8))
print(series(exp(t), t, 0, 5).removeO())

print(summation(k, (k, 1, 100)))
print(summation(k**2, (k, 1, n)).factor())
print(summation(1 / k**2, (k, 1, oo)))

s = Sum(1 / factorial(k), (k, 0, oo))
pprint(s)
print(s.doit())

The series of sin(t) around 0 contains terms up to t⁷ and the order term O(t**8), which removeO drops. The summation of k² up to a symbolic n gives the closed formula. The infinite sum of 1/k² is pi²/6, and the sum of 1/k! is E. As with derivatives, Sum creates an unevaluated sum.

$ python series_sums.py
t - t**3/6 + t**5/120 - t**7/5040 + O(t**8)
t**4/24 + t**3/6 + t**2/2 + t + 1
5050
n*(n + 1)*(2*n + 1)/6
pi**2/6
 ∞      
____    
╲       
 ╲      
  ╲   1 
  ╱   ──
 ╱    k!
╱       
‾‾‾‾    
k = 0   
E

Matrices

The Matrix class represents matrices with exact or symbolic entries.

matrices.py
from sympy import Matrix, pprint, symbols

A = Matrix([[2, 1], [1, 3]])
b = Matrix([3, 5])

pprint(A)
print(A.shape, A.det())
pprint(A.inv())
pprint(A * b)
print(A.solve(b))
print(A.eigenvals())

a = symbols('a')
M = Matrix([[a, 1], [1, a]])
print(M.det())
print(M.det().factor())

The determinant, inverse, and eigenvalues are computed exactly; the inverse has fractional entries and the eigenvalues contain square roots. The * operator multiplies matrices and solve solves the linear system A x = b. The entries can be symbols, so the determinant of M is a polynomial in a, which is singular for a = 1 and a = -1.

$ python matrices.py
⎡2  1⎤
⎢    ⎥
⎣1  3⎦
(2, 2) 5
⎡3/5   -1/5⎤
⎢          ⎥
⎣-1/5  2/5 ⎦
⎡11⎤
⎢  ⎥
⎣18⎦
Matrix([[4/5], [7/5]])
{5/2 - sqrt(5)/2: 1, sqrt(5)/2 + 5/2: 1}
a**2 - 1
(a - 1)*(a + 1)

Fast numerical evaluation

Calling subs and evalf in a loop is slow. The lambdify function translates an expression into an ordinary Python function that uses the math module (or NumPy).

lambdify_speed.py
import math
import time

from sympy import symbols, sin, exp, lambdify

x = symbols('x')
expr = sin(x) * exp(-x / 5)

f = lambdify(x, expr, 'math')
print(f(1.0))
print(expr.subs(x, 1.0).evalf())

xs = [i / 100 for i in range(2000)]

start = time.perf_counter()
slow = [float(expr.subs(x, v)) for v in xs]
t1 = time.perf_counter() - start

start = time.perf_counter()
fast = [f(v) for v in xs]
t2 = time.perf_counter() - start

print(all(math.isclose(a, b) for a, b in zip(slow, fast)))
print(f'subs:     {t1:.3f} s')
print(f'lambdify: {t2:.5f} s')

Both approaches give the same values for 2000 points, but the lambdified function is more than a thousand times faster, because it calls math.sin and math.exp directly instead of building and evaluating SymPy objects. The times vary from run to run.

$ python lambdify_speed.py
0.6889381730850401
0.688938173085040
True
subs:     0.825 s
lambdify: 0.00035 s

Plotting

The plot function draws expressions with Matplotlib.

plot_function.py
from sympy import symbols, sin, exp, plot

x = symbols('x')

p = plot(sin(x) * exp(-x / 5), exp(-x / 5), (x, 0, 20),
         title='Damped sine wave', ylabel='f(x)', show=False)
p[1].line_color = 'gray'
p.save('damped.png')

We plot the damped sine wave together with its envelope on the interval from 0 to 20. With show=False, the plot is not displayed and we can change it first; the second series is drawn in gray. The save method writes the image to a file.

Damped sine wave
Figure: Damped sine wave

Optimal open box

The last program combines the previous steps. An open box is made from a 30×20 cm sheet by cutting a square from each corner and folding up the sides. We look for the cut that gives the largest volume.

open_box.py
from sympy import symbols, diff, solveset, Interval, expand, pprint

# An open box is folded from a 30 x 20 cm sheet after cutting
# a square of side x from each corner. Which x gives the
# largest volume?

x = symbols('x', positive=True)
width, height = 30, 20

volume = expand(x * (width - 2*x) * (height - 2*x))
print('V(x) =', volume)

dv = diff(volume, x)
print("V'(x) =", dv)

valid = Interval.open(0, min(width, height) // 2)
candidates = solveset(dv, x, valid)
print('critical points:', candidates)

best = max(candidates, key=lambda c: volume.subs(x, c))
print()
print('exact cut:')
pprint(best)
print(f'cut:    {best.evalf(6)} cm')
print(f'volume: {volume.subs(x, best).evalf(7)} cm^3')
print(f'check:  {diff(dv, x).subs(x, best).evalf(4)} < 0')

The volume is x*(30 - 2*x)*(20 - 2*x). Its derivative is zero at two points, but only one lies in the interval (0, 10), where the box can be built, so solveset with the interval returns a single candidate. The exact answer contains a square root; evalf gives the numeric cut and volume. The negative second derivative confirms a maximum.

$ python open_box.py
V(x) = 4*x**3 - 100*x**2 + 600*x
V'(x) = 12*x**2 - 200*x + 600
critical points: {25/3 - 5*sqrt(7)/3}

exact cut:
25   5⋅√7
── - ────
3     3  
cut:    3.92375 cm
volume: 1056.306 cm^3
check:  -105.8 < 0

Source

SymPy documentation

SymPy introductory tutorial

In this article we have done symbolic mathematics with SymPy. See also Python Decimal, Python math.integer, Python statistics, and Python Matplotlib.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.