TExcelTAD
Home › Algebra › Algebra with SymPy

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:

python · try it yourself
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 x2x^2, 2*x means 2x2x. The table maps the notation used in the lessons to the code:

Written SymPy
2x2−3x2x^2 - 3x 2*x**2 - 3*x
x\sqrt{x} sqrt(x)
12x\frac{1}{2}x Rational(1, 2)*x or x/2
x=7x = 7 (an equation) Eq(x, 7)
∣x−3∣\lvert x - 3 \rvert Abs(x - 3)

Note: Write Rational(1, 2) rather than 1/2 when the fraction stands alone. Plain Python computes 1/2 as the float 0.5 before 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:

python · try it yourself
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 d=v⋅td = v \cdot t into t=dvt = \frac{d}{v}, 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:

python · try it yourself
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:

python · try it yourself
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 (−∞,5)(-\infty, 5), all numbers less than 5; Interval(1, 5) as the closed interval [1,5][1, 5], with both ends included; oo is SymPy's ∞\infty. Notice the second line: dividing by −2 flipped the inequality, which the Solving Inequalities lesson explains.

Your workflow in this course

  1. Solve the problem on paper.
  2. Check it with solve / solveset, or by substituting your answer with subs.
  3. If you need the formula in a program, lambdify it 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 (x−4)(x+6)(x - 4)(x + 6). Then factor the result back. Check both with SymPy.

Answer

x2+2x−24x^2 + 2x - 24, which factors to (x−4)(x+6)(x - 4)(x + 6).

Solution
(x−4)(x+6)=x2+6x−4x−24=x2+2x−24(x - 4)(x + 6) = x^2 + 6x - 4x - 24 = x^2 + 2x - 24
python · try it yourself
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 5(x−2)=3x+45(x - 2) = 3x + 4 by hand, then confirm with solve and with subs.

Answer

x=7x = 7

Solution
5x−10=3x+42x=14x=7\begin{aligned} 5x - 10 &= 3x + 4 \\ 2x &= 14 \\ x &= 7 \end{aligned}
python · try it yourself
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 A=π(R2−r2)A = \pi(R^2 - r^2). Use SymPy to solve it for RR, then lambdify the positive solution and evaluate it for A=50A = 50, r=2r = 2, rounded to 3 decimals.

Answer

R=Aπ+r2≈4.463R = \sqrt{\frac{A}{\pi} + r^2} \approx 4.463

Solution
A=π(R2−r2)Aπ=R2−r2R2=Aπ+r2R=Aπ+r2\begin{aligned} A &= \pi(R^2 - r^2) \\ \frac{A}{\pi} &= R^2 - r^2 \\ R^2 &= \frac{A}{\pi} + r^2 \\ R &= \sqrt{\frac{A}{\pi} + r^2} \end{aligned}

SymPy returns both signs of the square root; a radius is positive, so take the positive one.

python · try it yourself
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 A+πr2π\frac{\sqrt{A + \pi r^2}}{\sqrt{\pi}}, which equals Aπ+r2\sqrt{\frac{A}{\pi} + r^2}.

Exercise 4: An inequality

Use solveset to find all real xx with 7−2x>17 - 2x > 1, and say the answer in words.

Answer

Interval.open(-oo, 3): every number less than 3.

Solution
7−2x>1−2x>−6x<3(dividing by −2 flips the sign)\begin{aligned} 7 - 2x &> 1 \\ -2x &> -6 \\ x &< 3 && \text{(dividing by } -2 \text{ flips the sign)} \end{aligned}
python · try it yourself
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?

  1. SymPy cannot divide
  2. 1/3 is computed by Python as a float before SymPy sees it, so the result is not exact
  3. Rational is faster to type
  4. 1/3 raises an error

Which SymPy function returns the solution of 2x−1≤52x - 1 \le 5 as an interval?

  1. expand
  2. lambdify
  3. factor
  4. solveset

What does lambdify do?

  1. Turns a SymPy expression into a normal numeric Python function
  2. Solves an equation
  3. Simplifies an expression
  4. Draws a graph