If you're having problems with notebooks in SMC, note that you can also use IPython from a terminal.
Homework 2 will be posted by Thursday. Part of the homework will be to read this paper: "Best Practices for Scientific Computing, by G. Wilson, D. A. Aruliah", by C. T. Brown, et. al. that can be found at http://www.plosbiology.org/article/info%3Adoi%2F10.1371%2Fjournal.pbio.1001745
In [ ]:
%pylab inline
SymPy is a package of Python tools for symbolic calculations in algebra and calculus. This is notebook has a very brief demo of some features, but you can learn much more about it from various on-line resources such as:
You can do "from sympy import *" to get all of sympy in your namespace, but note that this will overwrite standard numpy variables such as pi and functions such as sin, cos, exp, sqrt, with sympy versions. Since we may want to mix symbolic and numerical computing, we will be explicit about what's coming from SymPy:
In [ ]:
import sympy as S # shorthand
In [ ]:
S.init_printing() # so symbolic math is printed nicely
In [ ]:
x = S.symbols('x') # defines a symbol
f = x**3 - 3*x**2 - 18*x + 40 # a new symbolic expression
f # print it nicely
In [ ]:
S.factor(f)
In [ ]:
S.diff(f,x) # differentiate f with respect to x
In [ ]:
f = (x**3 * S.exp(5*x)*S.cos(S.pi*x)) / (1 + S.sqrt(x))
f
In [ ]:
g = S.diff(f,x,n=3)
g
Note that if you "print g" it does not come out so pretty, but this might be more useful if you want to cut and paste this into a Fortran program, for example:
In [ ]:
print g
In [ ]:
g2 = g.subs(x, 0.2)
g2
Note this substituted 0.2 for $x$, but the special symbol $\pi$ has not be converted to a number. The SymPy function N converts special constants like $\pi$ and $e$ to numerical values:
In [ ]:
S.N(g2)
You can specify how many digits to use when it does this substitution, e.g.
In [ ]:
S.N(S.pi,n=50)
In [ ]:
def fvals(x, debug=False):
from sympy import symbols,diff,sqrt
# First specify f symbolically and differentiate using SymPy:
xs = symbols('xs')
fs = xs**2 - 2.
fprimes = diff(fs, xs)
# Now evaluate numerically at the value x passed in to this function:
f = fs.subs(xs, x)
fprime = fprimes.subs(xs, x)
# The next lines are just for illustrating that this is working:
if debug:
print "fs = ",fs
print "fprimes = ",fprimes
print "x = ",x
return f, fprime
# Try it out:
fv = fvals(3., debug=True)
print "fvals returns: ", fv
In [ ]:
def newton(fvals, x0, tol):
xk = x0
kmax = 30 # maximum number of iterations
print " k xk f(xk)"
for k in range(kmax):
fxk, fpxk = fvals(xk) # evaluate f(x) and f'(x)
print "%4i %22.15f %22.15f" % (k, xk, fxk)
if abs(fxk) < tol:
break #leave the loop if tolerance satisfied
xk = xk - fxk / fpxk # update xk using Newton's method
return xk
In [ ]:
newton(fvals, 2, 1e-10)
Remember you can get help in IPython by adding a ? to the end of an object and running the cell...
In [ ]:
S.integrate?
In [ ]:
S.diff?