from sympy import *
init_printing(use_latex='mathjax')
x, y, z = symbols('x,y,z')
n, m = symbols('n,m', integer=True)
%matplotlib inline
In this section we'll learn how to use our symbolic equations to drive numeric computations
.subs
and .evalf
¶The simplest (and slowest) ways to evaluate an expression numerically is with the .subs
and .evalf
methods
sin(x)
sin(x).subs({x: 0})
acos(x).subs({x: -1})
acos(x).subs({x: -1}).evalf()
acos(x).subs({x: -1}).evalf(n=100)
In a previous section we computed the following symbolic integral
$$ \int_y^z x^n dx $$result = integrate(x**n, (x, y, z))
result
Use .subs
and a dictionary with keys n, y, z
to evaluate this result when
n == 2
y == 0
z == 3
# Evaluate the resulting integral on the above values
This integral takes on a special form when $n = -1$. Use subs to find the expression when
n == -1
y == 5
z == 100
Then use .evalf
to evaluate this subs-ed expression as a float.
# Evaluate the resulting integral for the values {n: -1, y: 5, z: 100}
# Then use evalf to get a numeric result
lambdify
¶The .subs
and .evalf
methods are great for when you want to evaluate an expression at a single point. When you want to evaluate your expression on lots of points they quickly become slow.
To resolve this problem SymPy can rewrite its expressions as normal Python functions using the math
library, vectorized computations using the NumPy library, C or Fortran Code using code printers, or even more sophisticated systems.
We'll talk about some of the more advanced topics later. For now, lambdify...
# function = lambdify(input, output)
f = lambdify(x, x**2)
f(3)
import numpy as np
f = lambdify(x, x**2, 'numpy') # Use numpy backend
data = np.array([1, 2, 3, 4, 5])
f(data)
array([ 1, 4, 9, 16, 25])
Here is a radial wave function for the Carbon atom at $n=3$, $l=1$
from sympy.physics.hydrogen import R_nl
n = 3
l = 1
r = 6 # Carbon
expr = R_nl(n, l, x, r)
expr
Create a function, f
, that evaluate this expression using the 'numpy'
backend
# Create Numpy function mapping x to expr with the numpy backend
We can plot your function from $x \in [0, 5]$ with the following numpy/matplotlib code
from matplotlib.pyplot import plot
nx = np.linspace(0, 5, 1000)
plot(nx, f(nx))
Create a numpy function that computes the derivative of our expression. Plot the result alongside the original.
# Compute derivative of expr with respect to x
# Create new fprime function using lambdify
# Plot results alongside f(nx)