In this section we learn to do the following:
Just like NumPy and Pandas replace functions like
log to powerful numeric implementations, SymPy replaces
log with powerful mathematical implementations.
from sympy import * init_printing() # Set up fancy printing
import math math.sqrt(2)
sqrt(2) # This `sqrt` comes from SymPy
Use the function
-1 to find when cosine equals
-1. Try this same function with the math library. Do you get the same result?
# Call acos on -1 to find where on the circle the x coordinate equals -1
# Call `math.acos` on -1 to find the same result using the builtin math module. # Is the result the same? # What do you think `numpy.acos` give you?
Just like the NumPy
ndarray or the Pandas
DataFrame, SymPy has the
Symbol, which represents a mathematical variable.
We create symbols using the function
symbols. Operations on these symbols don't do numeric work like with NumPy or Pandas, instead they build up mathematical expressions.
x, y, z = symbols('x,y,z') alpha, beta, gamma = symbols('alpha,beta,gamma')
x + 1
log(alpha ** beta) + gamma
sin(x)**2 + cos(x)**2
?, ? = symbols('?')
sqrt, and Python's arithmetic operators like
+, -, *, ** to create the standard bell curve with SymPy objects
One of the most commonly requested operations in SymPy is the derivative. To take the derivative of an expression use the
(x**2 + x*y + y**2).diff(x)
(x**2 + x*y + y**2).diff(y)
mu, sigma = symbols('mu,sigma')
bell = exp((x - mu)**2 / sigma**2) bell
Take the derivative of this expression with respect to $x$
There are three symbols in that expression. We normally are interested in the derivative with repspect to
x, but we could just as easily ask for the derivative with respect to
sigma. Try this now
# Derivative of bell curve with respect to sigma
The second derivative of an expression is just the derivative of the derivative. Chain
.diff( ) calls to find the second and third derivatives of your expression.
# Find the second and third derivative of `bell`
SymPy has a number of useful routines to manipulate expressions. The most commonly used function is
expr = sin(x)**2 + cos(x)**2 expr
You might notice that this expression has lots of shared structure. We can factor out some terms to simplify this expression.
simplify on this expression and observe the result.
# Call simplify on the third derivative of the bell expression
sympify function transforms Python objects (ints, floats, strings) into SymPy objects (Integers, Reals, Symbols).
note the difference between
simplify. These are not the same function.
sympify('r * cos(theta)^2')
It's useful whenever you interact with the real world, or for quickly copy-pasting an expression from an external source.