A little SymPy

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.

Importing SymPy

When using SymPy, it's common to just import the whole library into the global namespace, like so:

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

Basic usage

Typically, we need to define one or more variables as symbolic.

In [2]:
x = var('x')

We define functions as normal. Note that we can plug the symbolic variable x in, as well as any real number.

In [3]:
def f(x): return x**2 - 2
[f(x), f(2)]
Out[3]:
[x**2 - 2, 2]

We can differentiate our function.

In [4]:
diff(f(x),x)
Out[4]:
2*x

And find its roots symbolically.

In [5]:
solve(f(x),x)
Out[5]:
[-sqrt(2), sqrt(2)]

Of course, SymPy can do a whole lot more!

Newton's method

We can use Sympy to automate the process of finding Newton's method iteration function.

In [6]:
from sympy import *
x = var('x')
def f(x): return sin(1/x)-x
expr = x - f(x)/diff(f(x),x)
expr
Out[6]:
x - (-x + sin(1/x))/(-1 - cos(1/x)/x**2)

We can turn expr into a fast, numeric function using lambdify:

In [7]:
n = lambdify(x,expr)
n(1)
Out[7]:
0.8970792846390281

OK, let's use it!

In [8]:
x = 1
cnt = 0
while abs(f(x))>10**-15 and cnt<10:
    x = n(x)
    cnt = cnt+1
x,cnt
Out[8]:
(0.8975394612804872, 3)