Introduction to SymPy

A conjecture is a mathematical statement that is believed to be true but has not been proven. A single counterexample, meaning one case where the statement fails, is enough to disprove a conjecture. Some counterexamples can be found through numerical computations; others require exact symbolic calculations.

SymPy is a Python package for symbolic mathematics. SymPy works with exact values and expressions, like \(\sqrt{8}\) or \(x^2 - 1\), instead of approximating them numerically with floats.

import numpy as np
import sympy as sy

print(np.sqrt(8))       # Floating-point approximation of the square root of 8.
print(sy.sqrt(8))       # Exact symbolic representation of the square root of 8.
print(sy.sqrt(8) ** 2)  # Exactly 8, with no roundoff error!
2.8284271247461903
2*sqrt(2)
8

Symbols and Expressions

A symbol is a SymPy variable that stands for an unknown quantity, like \(x\) in algebra. The sy.symbols() function accepts a string of names separated by spaces and returns one symbol per name. Arithmetic with symbols produces an expression, which SymPy stores exactly instead of evaluating it to a number. The subs() method substitutes values for the symbols in an expression.

x, y = sy.symbols("x y")
expr = (x + y) ** 2 - 2 * x * y

print(expr)
print(expr.subs(x, 3))          # Replace x with 3.
print(expr.subs({x: 3, y: 4}))  # Replace x with 3 and y with 4.
-2*x*y + (x + y)**2
-6*y + (y + 3)**2
25

In a notebook, ending a cell with an expression displays that expression in rendered LaTeX.

expr
\[\displaystyle - 2 x y + \left(x + y\right)^{2}\]

Exponents

Just as in standard Python, SymPy uses ** for exponents, not ^.

Fractions

It is easy to mix symbolic expressions with floats.

print(x + 1 / 3)
x + 0.333333333333333

Here, Python evaluates 1/3 as a float before SymPy sees it. Use sy.Rational(1, 3) to keep a fraction exact.

print(x + sy.Rational(1, 3))
x + 1/3

Simplification

SymPy can rewrite an expression in an equivalent form.

Function

Effect

sy.expand()

Multiply out products and powers.

sy.factor()

Factor a polynomial as far as possible using integer coefficients.

sy.simplify()

Apply many heuristics to rewrite an expression in a simpler form.

print(sy.expand((x + 1) ** 3))
print(sy.factor(x**3 - x))
print(sy.simplify((x**2 - 1) / (x - 1)))
print(sy.simplify(sy.sin(x) ** 2 + sy.cos(x) ** 2))
x**3 + 3*x**2 + 3*x + 1
x*(x - 1)*(x + 1)
x + 1
1

Checking Equality

The == operator checks whether two expressions are written the same way, not whether they are mathematically equal.

print((x + 1) ** 2 == x**2 + 2 * x + 1)
False

For many expressions, sy.simplify(a - b) == 0 can confirm that a and b are equal. However, simplify() is heuristic and is not a general test for equality.

Problem 1

Disprove: If \(p\in\mathbb{N}\), then \((x+1)^p-(x-1)^p = 2p x^{p-1}\) for all \(x\in\mathbb{R}\).

Write a function named symmetric_power() that accepts a positive integer \(p\in\mathbb{N}\). Return True if \((x+1)^p-(x-1)^p = 2p x^{p-1}\) for all \(x\in\mathbb{R}\) and False otherwise.

Use symmetric_power() to find the smallest counterexample, meaning the smallest \(p_0\) such that \((x+1)^{p_0}-(x-1)^{p_0} \neq 2p_0 x^{p_0-1}\), by checking \(p = 1,2,\ldots\) until symmetric_power(p) returns False. Store the value of \(p_0\) as the variable problem1_counterexample.

More SymPy Features

Bonus Material

The following material is not needed for this lab assignment, but it is useful information.

Linear Algebra

The sy.Matrix() type stores a matrix with exact entries, so determinants, inverses, and solutions to linear systems come out as exact fractions instead of floats. A matrix is created from a list of its rows, and a column vector from a list of its entries.

Method

Returns

A.det()

The determinant \(\det(A)\).

A.inv()

The inverse \(A^{-1}\).

A.solve(b)

The solution \(\mathbf{x}\) to \(A\mathbf{x} = \mathbf{b}\), when \(A\) is invertible.

A.rref()

The reduced row echelon form of \(A\) and the indices of its pivot columns.

A.nullspace()

A list of vectors that form a basis for the null space of \(A\).

A = sy.Matrix([
    [2, 1],
    [1, 3],
])
b = sy.Matrix([1, 2])  # A column vector.

print(A.det())
print(A.inv())         # Exact fractions instead of floats.
print(A @ A.inv())     # The 2 x 2 identity matrix.
print(A.solve(b))      # The solution to Ax = b.
5
Matrix([[3/5, -1/5], [-1/5, 2/5]])
Matrix([[1, 0], [0, 1]])
Matrix([[1/5], [3/5]])

For a matrix that is not invertible, the reduced row echelon form and null space describe the solutions instead.

B = sy.Matrix([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
])
print(B.rref())  # Pivots in columns 0 and 1 only.
print(B.nullspace())
(Matrix([
[1, 0, -1],
[0, 1,  2],
[0, 0,  0]]), (0, 1))
[Matrix([
[ 1],
[-2],
[ 1]])]

Matrices may also contain symbols, which makes SymPy a tool for deriving formulas, such as the determinant and inverse of a general \(2 \times 2\) matrix.

a, b, c, d, e, f, g, h, i = sy.symbols("a b c d e f g h i")
M2 = sy.Matrix([
    [a, b],
    [c, d],
])
print(M2.det())
print(M2.inv())

M3 = sy.Matrix([
    [a, b, c],
    [d, e, f],
    [g, h, i],
])
M3.inv()
a*d - b*c
Matrix([[d/(a*d - b*c), -b/(a*d - b*c)], [-c/(a*d - b*c), a/(a*d - b*c)]])
\[\begin{split}\displaystyle \left[\begin{matrix}\frac{e i - f h}{a e i - a f h - b d i + b f g + c d h - c e g} & \frac{- b i + c h}{a e i - a f h - b d i + b f g + c d h - c e g} & \frac{b f - c e}{a e i - a f h - b d i + b f g + c d h - c e g}\\\frac{- d i + f g}{a e i - a f h - b d i + b f g + c d h - c e g} & \frac{a i - c g}{a e i - a f h - b d i + b f g + c d h - c e g} & \frac{- a f + c d}{a e i - a f h - b d i + b f g + c d h - c e g}\\\frac{d h - e g}{a e i - a f h - b d i + b f g + c d h - c e g} & \frac{- a h + b g}{a e i - a f h - b d i + b f g + c d h - c e g} & \frac{a e - b d}{a e i - a f h - b d i + b f g + c d h - c e g}\end{matrix}\right]\end{split}\]

Matrix Multiplication

For SymPy matrices, both A @ B and A * B mean matrix multiplication. This differs from NumPy arrays, where A * B multiplies entry by entry.

Conversion to NumPy

The function sy.lambdify() converts an expression to a Python function that works on NumPy arrays.

import matplotlib.pyplot as plt

x = sy.symbols("x")
f = sy.lambdify(x, x**2 - 1)

# f() is a function that can be called with a NumPy array as the argument.
t = np.linspace(-2, 2, 400)
plt.plot(t, f(t))
plt.show()
../_images/ae3b819d03b7e2d977850b0f1cc9eb551c6ddb2dab534f458d3fd5267386ce39.png

LaTeX

The function sy.latex() converts an expression to LaTeX source code.

expr = sy.cos(x**2 / 2)
print(sy.latex(expr))

expr
\cos{\left(\frac{x^{2}}{2} \right)}
\[\displaystyle \cos{\left(\frac{x^{2}}{2} \right)}\]