Just like NumPy and Pandas replace functions like sin, cos, exp, and log to powerful numeric implementations, SymPy replaces sin, cos, exp and log with powerful mathematical implementations.
In [1]:
from sympy import *
init_printing() # Set up fancy printing
In [2]:
import math
math.sqrt(2)
Out[2]:
In [3]:
sqrt(2) # This `sqrt` comes from SymPy
Out[3]:
In [4]:
cos(0)
Out[4]:
In [ ]:
# Call acos on -1 to find where on the circle the x coordinate equals -1
In [ ]:
# Call `math.acos` on -1 to find the same result using the builtin math module.
# Is the result the same?
# What does `numpy.arccos` give you?
In [5]:
x, y, z = symbols('x,y,z')
alpha, beta, gamma = symbols('alpha,beta,gamma')
In [6]:
x + 1
Out[6]:
In [7]:
log(alpha**beta) + gamma
Out[7]:
In [8]:
sin(x)**2 + cos(x)**2
Out[8]:
In [ ]:
?, ? = symbols('?')
In [ ]:
exp(?)
In [9]:
(x**2).diff(x)
Out[9]:
In [10]:
sin(x).diff(x)
Out[10]:
In [11]:
(x**2 + x*y + y**2).diff(x)
Out[11]:
In [19]:
diff(x**2 + x*y + y**2, y) # diff is also available as a function
Out[19]:
In [13]:
mu, sigma = symbols('mu,sigma')
In [14]:
bell = exp((x - mu)**2 / sigma**2)
bell
Out[14]:
Take the derivative of this expression with respect to $x$
In [ ]:
?.diff(?)
In [ ]:
# Derivative of bell curve with respect to sigma
In [ ]:
# Find the second and third derivative of `bell`
In [15]:
expr = sin(x)**2 + cos(x)**2
expr
Out[15]:
In [16]:
simplify(expr)
Out[16]:
In [21]:
bell.diff(x).diff(x).diff(x)
Out[21]:
You might notice that this expression has lots of shared structure. We can factor out some terms to simplify this expression.
Call simplify on this expression and observe the result.
In [ ]:
# Call simplify on the third derivative of the bell expression
In [18]:
sympify('r * cos(theta)^2')
Out[18]:
It's useful whenever you interact with the real world, or for quickly copy-pasting an expression from an external source.