In [ ]:
from sympy import *
init_printing(use_latex='mathjax')
x, y, z = symbols('x,y,z')
n, m = symbols('n,m', integer=True)

In [ ]:
%matplotlib inline


# Numeric Evaluation¶

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

In [ ]:
sin(x)

In [ ]:
sin(x).subs({x: 0})

In [ ]:
acos(x).subs({x: -1})

In [ ]:
acos(x).subs({x: -1}).evalf()

In [ ]:
acos(x).subs({x: -1}).evalf(n=100)


### Exercise¶

In a previous section we computed the following symbolic integral

$$\int_y^z x^n dx$$
In [ ]:
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
In [ ]:
# Evaluate the resulting integral on the above values


### Exercise¶

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.

In [ ]:
# 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...

In [ ]:
# function = lambdify(input, output)

f = lambdify(x, x**2)
f(3)

In [ ]:
import numpy as np
f = lambdify(x, x**2, 'numpy')  # Use numpy backend
data = np.array([1, 2, 3, 4, 5])
f(data)


### Exercise¶

Here is a radial wave function for the Carbon atom at $n=3$, $l=1$

In [ ]:
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

In [ ]:
# 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

In [ ]:
from matplotlib.pyplot import plot
nx = np.linspace(0, 5, 1000)
plot(nx, f(nx))


### Exercise¶

Create a numpy function that computes the derivative of our expression. Plot the result alongside the original.

In [ ]:
# Compute derivative of expr with respect to x

In [ ]:
# Create new fprime function using lambdify

In [ ]:
# Plot results alongside f(nx)