Python-Unit III
Python-Unit III
Introduction to SymPy
1
2 Lab 10. Introduction to SymPy
SymPy has its own version for each of the standard mathematical functions like sin(x), log(x),
√
and x, and includes predened variables for special numbers such as π. The naming conventions
for most functions match NumPy, but some of the built-in constants are named slightly dierently.
√
sin(x) arcsin(x) sinh(x) ex log(x) x
Functions
sy.sin() sy.asin() sy.sinh() sy.exp() sy.log() sy.sqrt()
√
π e i = −1 ∞
Constants
sy.pi sy.E sy.I sy.oo
Other trigonometric functions like cos(x) follow the same naming conventions. For a complete list of
SymPy functions, see http://docs.sympy.org/latest/modules/functions/index.html.
Achtung!
Always use SymPy functions and constants when creating expressions instead of using NumPy's
functions and constants. Later we will show how to make NumPy and SymPy cooperate.
>>> x = sy.symbols('x')
>>> np.exp(x) # Try to use NumPy to represent e**x.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Symbol' object has no attribute 'exp'
Note
SymPy denes its own numeric types for integers, oats, and rational numbers. For example,
the sy.Rational class is similar to the standard library's fractions.Fraction class, and
should be used to represent fractions in SymPy expressions.
>>> x = sy.symbols('x')
>>> (2/3) * sy.sin(x) # 2/3 returns a float, not a rational.
0.666666666666667*sin(x)
Always be aware of which numeric types are being used in an expression. Using rationals and
integers where possible is important for simplifying expressions.
3
2 x2 −y 3
Problem 1. Write a function that returns the expression
5e cosh(x + y) + 7 log(xy + 1)
symbolically. Make sure that the fractions remain symbolic.
4
X 5
Y
x + iy x + iy
i=1 i=0
Simplifying Expressions
The expressions for the summation and product in the previous example are automatically simplied.
More complicated expressions can be simplied with one or more of the following functions.
Function Description
sy.cancel() Cancel common factors in the numerator and denominator.
sy.expand() Expand a factored expression.
sy.factor() Factor an expanded expression.
sy.radsimp() Rationalize the denominator of an expression.
sy.simplify() Simplify an expression.
sy.trigsimp() Simplify only the trigonometric parts of the expression.
>>> x = sy.symbols('x')
>>> expr = (x**2 + 2*x + 1) / ((x+1)*((sy.sin(x)/sy.cos(x))**2 + 1))
>>> print(expr)
(x**2 + 2*x + 1)/((x + 1)*(sin(x)**2/cos(x)**2 + 1))
>>> sy.simplify(expr)
(x + 1)*cos(x)**2
The generic sy.simplify() tries to simplify an expression in any possible way. This is often
computationally expensive; using more specic simpliers when possible reduces the cost.
4 Lab 10. Introduction to SymPy
Achtung!
1. Simplications return new expressions; they do not modify existing expressions in place.
2. The == operator compares two expressions for exact structural equality, not algebraic
equivalence. Simplify or expand expressions before comparing them with ==.
3. Expressions containing oats may not simplify as expected. Always use integers and
SymPy rationals in expressions when appropriate.
>>> sy.factor(x**2.0 - 1)
x**2.0 - 1 # Factorization fails due to the 2.0.
5
Problem 2. Write a function that computes and simplies the following expression.
5 X
Y 5
j(sin(x) + cos(x))
i=1 j=i
Evaluating Expressions
Every SymPy expression has a subs() method that substitutes one variable for another. The result is
usually still a symbolic expression, even if a numerical value is used in the substitution. The evalf()
method actually evaluates the expression numerically after all symbolic variables have been assigned
a value. Both of these methods can accept a dictionary to reassign multiple symbols simultaneously.
These operations are good for evaluating an expression at a single point, but it is typically more
useful to turn the expression into a reusable numerical function. To this end, sy.lambdify() takes
in a symbolic variable (or list of variables) and an expression, then returns a callable function that
corresponds to the expression.
Note
N
X xn
ex ≈ . (10.1)
n=0
n!
Write a function that accepts an integer N. Dene an expression for (10.1), then substitute in
2
−y 2 for x to get a truncated Maclaurin series of e−y . Lambdify the resulting expression and
2
plot the series on the domain y ∈ [−2, 2]. Plot e−y over the same domain for comparison.
(Hint: use sy.factorial() to compute the factorial.)
Call your function with increasing values of N to check that the series converges correctly.
The curve is not the image of a single function (such a function would fail the vertical line test),
so the best way to plot it is to convert (10.2) to a pair of parametric equations that depend on
the angle parameter θ.
Construct an expression for the nonzero side of (10.2) and convert it to polar coordinates
with the substitutions x = r cos(θ) andy = r sin(θ). Simplify the result, then solve it for r.
There are two solutions due to the presence of an r2 term; pick one and lambdify it to get
a function r(θ). Use this function to plot x(θ) = r(θ) cos(θ) against y(θ) = r(θ) sin(θ) for
θ ∈ [0, 2π].
(Hint: use sy.Rational() for the fractional exponent.)
8 Lab 10. Introduction to SymPy
Linear Algebra
Sympy can also solve systems of equations. Ax = b is solved in a
A system of linear equations
slightly dierent way than in NumPy and SciPy: instead of dening the matrix A and the vector b
separately, dene the augmented matrix M = [A | b] and call sy.solve_linear_system() on M .
SymPy matrices are dened with sy.Matrix(), with the same syntax as 2-dimensional NumPy
arrays. For example, the following code solves the system given below.
x + y + z = 5
2x + 4y + 3z = 2
5x + 10y + 2z = 4
SymPy matrices support the standard matrix operations of addition +, subtraction -, and
multiplication @. Additionally, SymPy matrices are equipped with many useful methods, some of
which are listed below. See http://docs.sympy.org/latest/modules/matrices/matrices.html
for more methods and examples.
Method Returns
det() The determinant.
eigenvals() The eigenvalues and their multiplicities.
eigenvects() The eigenvectors and their corresponding eigenvalues.
inv() The matrix inverse.
is_nilpotent() True if the matrix is nilpotent.
norm() The Frobenius, ∞, 1, or 2 norm.
nullspace() The nullspace as a list of vectors.
rref() The reduced row-echelon form.
singular_values() The singular values.
Achtung!
Problem 5. Find the eigenvalues of the following matrix by solving for λ in the characteristic
equation det(A − λI) = 0.
x−y x 0
A= x x−y x
0 x x−y
Also compute the eigenvectors by solving the linear system A − λI = 0 for each eigenvalue λ.
Return a dictionary mapping the eigenvalues to their eigenvectors.
(Hint: the nullspace() method may be useful.)
Check that Av = λv for each eigenvalue-eigenvector pair (λ, v). Compare your results to
the eigenvals() and eigenvects() methods for SymPy matrices.
Calculus
SymPy is also equipped to perform standard calculus operations, including derivatives, integrals, and
taking limits. Like other elements of SymPy, calculus operations can be temporally expensive, but
they give exact solutions whenever solutions exist.
Differentiation
The command sy.Derivative() creates a closed form, unevaluated derivative of an expression.
This
d
is like putting in front of an expression without actually calculating the derivative symbolically.
dx
The resulting expression has a doit() method that can be used to evaluate the actual derivative.
sy.diff() immediately takes the derivative of an expression.
Equivalently,
Both sy.Derivative() and sy.diff() accept a single expression, then the variable or variables
that the derivative is being taken with respect to.
Use SymPy to nd all critical points of p and classify each as a local minimum or a local
maximum. Plot p(x) over x ∈ [−5, 5] and mark each of the minima in one color and the
maxima in another color. Return the collections of local minima and local maxima as sets.
∂f1 ∂f1 ∂f1
∂x1 ∂x2 ∂x3
x1
h
∂f ∂f ∂f
i f1 (x)
J= = , where f (x) = , x = x2 .
∂x1 ∂x2 ∂x3 f2 (x)
∂f2 ∂f2 ∂f2
∂x1 ∂x2 ∂x3
x3
To calculate the Jacobian matrix of a multivariate function with SymPy, dene that function
as a symbolic matrix (sy.Matrix()) and use its jacobian() method. The method requires a list of
variables that prescribes the ordering of the dierentiation.
Integration
The function sy.Integral() creates an unevaluated integral expression. This is like putting an
integral sign in front of an expression without actually evaluating the integral symbolically or nu-
merically. The resulting expression has adoit() method that can be used to evaluate the actual
integral. Equivalently, sy.integrate() immediately integrates an expression.
Both sy.Derivative() and sy.diff() accept a single expression, then a tuple or tuples con-
taining the variable of integration and, optionally, the bounds of integration.
Problem 7. Let f : R3 → R be a smooth function. The volume integral of f over the sphere
S of radius r can written in spherical coordinates as
ZZZ Z π Z 2π Z r
f (x, y, z)dV = f (h1 (ρ, θ, φ), h2 (ρ, θ, φ), h3 (ρ, θ, φ))| det(J)| dρ dθ dφ,
0 0 0
S
Calculate the volume integral of f (x, y, z) = (x2 + y 2 + z 2 )2 over the sphere of radius r.
Lambdify the resulting expression (with r as the independent variable) and plot the integral
value for r ∈ [0, 3]. In addition, return the value of the integral when r = 2.
(Hint: simplify the integrand before computing the integral. In this case, | det(J)| = − det(J).)
8748
To check your answer, when r = 3, the value of the integral is
7 π.
Achtung!
SymPy isn't perfect. It solves some integrals incorrectly, simplies some expressions poorly,
and is signicantly slower than numerical computations. However, it is generally very useful for
simplifying parts of an algorithm, getting exact answers, and handling tedious algebra quickly.
12 Lab 10. Introduction to SymPy
Additional Material
Pretty Printing
SymPy expressions, especially complicated ones, can be hard to read. Calling sy.init_printing()
changes the way that certain expressions are displayed to be more readable; in a Jupyter Notebook,
A
the rendering is done with L TEX, as displayed below. Furthermore, the function sy.latex() converts
A
an expression into actual L TEX code for use in other settings.
Limits
Limits can be expressed, similar to derivatives or integrals, with sy.Limit(). Alternatively, sy.
limit() (lowercase) evaluates a limit directly.
Use limits instead of the subs() method when the value to be substituted is ∞ or is a singularity.
>>> expr = x / 2**x
>>> expr.subs(x, sy.oo)
nan
>>> sy.limit(expr, x, sy.oo)
0
Numerical Integration
Many integrals cannot be solved analytically. As an alternative to the doit() method, the as_sum()
method approximates the integral with a summation. This method accepts the number of terms
to use and a string indicating which approximation rule to use ("left", "right", "midpoint", or
"trapezoid").
>>> x = sy.symbols('x')
Differential Equations
SymPy can be used to solve both ordinary and partial dierential equations. The documentation for
working with PDE functions is at http://docs.sympy.org/dev/modules/solvers/pde.html
dx
The general form of a rst-order dierential equation is
dt = f (x(t), t). To represent the
unknown function x(t), use sy.Function(). Just as sy.solve() is used to solve an expression for
a given variable, sy.dsolve() solves an ODE for a particular function. When there are multiple
solutions, sy.dsolve() returns a list; when arbitrary constants are involved they are given as C1, C2,
and so on. Use sy.checkodesol() to check that a function is a solution to a dierential equation.
>>> t = sy.symbols('t')
>>> x = sy.Function('x')
Since there are many types of ODEs, sy.dsolve() may also take a hint indicating what solving
strategy to use. See sy.ode.allhints sy.classify_ode() to see
for a list of possible hints, or use
the list of hints that may apply to a particular equation.
14 Lab 10. Introduction to SymPy
Bibliography
+
[MSP 17] Aaron Meurer, Christopher P Smith, Mateusz Paprocki, Ondrej Certík, Sergey B Kir-
pichev, Matthew Rocklin, AMiT Kumar, Sergiu Ivanov, Jason K Moore, Sartaj Singh,
et al. Sympy: symbolic computing in python. PeerJ Computer Science, 3:e103, 2017. [1]
15