Algebra with SymPy
SymPy is a Python library that does algebra with symbols instead of numbers: it expands, factors and simplifies expressions, solves equations and inequalities exactly, and turns a finished formula into a fast numeric function. This lesson is a tour of the dozen commands the rest of the course uses to check hand calculations.
Symbols and expressions
In plain Python, x + x fails unless x already holds a number. In SymPy you first declare x as a symbol, and then expressions built from it stay symbolic:
from sympy import symbols, expand, factor, simplify
x, y = symbols("x y")
e = 3*x + 2*y - x + 5
print(e) # like terms are combined automatically
print(expand((x + 2)*(x - 5))) # multiply out
print(factor(x**2 - 9)) # undo a product
print(simplify((x**2 - 1)/(x - 1)))2*x + 2*y + 5
x**2 - 3*x - 10
(x - 3)*(x + 3)
x + 1
SymPy prints with Python syntax: x**2 means , 2*x means . The table maps the notation used in the lessons to the code:
| Written | SymPy |
|---|---|
2*x**2 - 3*x |
|
sqrt(x) |
|
Rational(1, 2)*x or x/2 |
|
| (an equation) | Eq(x, 7) |
Abs(x - 3) |
Note: Write
Rational(1, 2)rather than1/2when the fraction stands alone. Plain Python computes1/2as the float0.5before SymPy ever sees it, and you lose exactness.
Solving equations
Eq(left, right) builds an equation (the = sign in Python already means assignment, and == compares structure). solve(equation, variable) returns a list of solutions:
from sympy import symbols, Eq, solve, Rational
x, t, v, d = symbols("x t v d")
print(solve(Eq(4*x - 7, 2*x + 9), x)) # one solution
print(solve(Eq(x**2, 2*x + 15), x)) # two solutions
print(solve(Eq(x/3 + Rational(1, 2), 2), x))
print(solve(Eq(d, v*t), t)) # solve a formula for t[8]
[-3, 5]
[9/2]
[d/v]
The last line shows a literal equation: SymPy rearranges into , exactly what the lesson Solving Formulas for a Variable does by hand.
Substituting and lambdify
subs plugs values into an expression and is the quickest way to check an answer. lambdify turns an expression into an ordinary Python (or NumPy) function, which is how a formula derived symbolically ends up inside a real program:
from sympy import symbols, lambdify
import numpy as np
x = symbols("x")
f = 2*x**2 - 3*x + 1
print(f.subs(x, 4)) # 2·16 − 12 + 1
print(f.subs(x, 0.5)) # 0.5 is a root
g = lambdify(x, f, "numpy")
xs = np.array([0, 1, 2, 3])
print([int(v) for v in g(xs)])21
0
[1, 0, 3, 10]
Inequalities with solveset
solve is for equations. For an inequality, solveset returns the solution as a set of real numbers, written in interval notation:
from sympy import symbols, solveset, S, Abs
x = symbols("x")
print(solveset(3*x - 4 < 11, x, domain=S.Reals))
print(solveset(-2*x + 1 >= 7, x, domain=S.Reals))
print(solveset(Abs(x - 3) <= 2, x, domain=S.Reals))
print(solveset(x**2 > 4, x, domain=S.Reals))Interval.open(-oo, 5)
Interval(-oo, -3)
Interval(1, 5)
Union(Interval.open(-oo, -2), Interval.open(2, oo))
Read Interval.open(-oo, 5) as , all numbers less than 5; Interval(1, 5) as the closed interval , with both ends included; oo is SymPy's . Notice the second line: dividing by −2 flipped the inequality, which the Solving Inequalities lesson explains.
Your workflow in this course
- Solve the problem on paper.
- Check it with
solve/solveset, or by substituting your answer withsubs. - If you need the formula in a program,
lambdifyit or copy it into a normal function.
Tip: SymPy is a checker, not a teacher. When it disagrees with you, find the step where you went wrong; that is where the learning happens.
Exercises
Exercise 1: Expand and factor
By hand, expand . Then factor the result back. Check both with SymPy.
Answer
, which factors to .
Solution
from sympy import symbols, expand, factor
x = symbols("x")
e = expand((x - 4)*(x + 6))
print(e, "|", factor(e))x**2 + 2*x - 24 | (x - 4)*(x + 6)
Exercise 2: Solve and check
Solve by hand, then confirm with solve and with subs.
Answer
Solution
from sympy import symbols, Eq, solve
x = symbols("x")
print(solve(Eq(5*(x - 2), 3*x + 4), x))
print((5*(x - 2)).subs(x, 7), (3*x + 4).subs(x, 7))[7]
25 25
Exercise 3: A formula for code
The area of a ring (annulus) is . Use SymPy to solve it for , then lambdify the positive solution and evaluate it for , , rounded to 3 decimals.
Answer
Solution
SymPy returns both signs of the square root; a radius is positive, so take the positive one.
from sympy import symbols, Eq, solve, pi, lambdify
A, R, r = symbols("A R r", positive=True)
sol = solve(Eq(A, pi*(R**2 - r**2)), R)
print(sol)
f = lambdify((A, r), sol[0])
print(round(f(50, 2), 3))[sqrt(A + pi*r**2)/sqrt(pi)]
4.463
SymPy writes , which equals .
Exercise 4: An inequality
Use solveset to find all real with , and say the answer in words.
Answer
Interval.open(-oo, 3): every number less than 3.
Solution
from sympy import symbols, solveset, S
x = symbols("x")
print(solveset(7 - 2*x > 1, x, domain=S.Reals))Interval.open(-oo, 3)
Test yourself
Why write Rational(1, 3) instead of 1/3 in a SymPy expression?
- SymPy cannot divide
1/3is computed by Python as a float before SymPy sees it, so the result is not exact- Rational is faster to type
1/3raises an error
Which SymPy function returns the solution of as an interval?
- expand
- lambdify
- factor
- solveset
What does lambdify do?
- Turns a SymPy expression into a normal numeric Python function
- Solves an equation
- Simplifies an expression
- Draws a graph