To be clear, the algorithms behind symbolic computation are not part of this class. Nonetheless, it's sometimes nice to have a symbolic tool in our toolbox. Anaconda includes a library called SymPy for exactly this purpose and I think it's reasonable to take a quick look at it.
Warning: SymPy is nowhere near as powerful as Mathematica. It's just kind of convenient to have around when working with Python.
When using SymPy, it's common to just import the whole library into the global namespace, like so:
from sympy import *
We do this, in part, because one major objective of SymPy is to define a standalone computer algebra system. In that context, it's nice to have all that functionality right at your fingertips.
Typically, we need to define one or more variables as symbolic.
x = var('x')
We define functions as normal. Note that we can plug the symbolic variable x
in, as well as any real number.
def f(x): return x**2 - 2
[f(x), f(2)]
We can differentiate our function.
diff(f(x),x)
And find its roots symbolically.
solve(f(x),x)
Of course, SymPy can do a whole lot more!
We can use Sympy to automate the process of finding Newton's method iteration function.
from sympy import *
x = var('x')
def f(x): return sin(1/x)-x
expr = x - f(x)/diff(f(x),x)
expr
We can turn expr
into a fast, numeric function using lambdify
:
n = lambdify(x,expr)
n(1)
OK, let's use it!
x = 1
cnt = 0
while abs(f(x))>10**-15 and cnt<10:
x = n(x)
cnt = cnt+1
x,cnt