I am finally learning Python and I am absolutely loving it. I never bothered learning the language before because I thought it was to similar to Perl. However, I am finding that it is not the case. The code seems so much cleaner and contains much better mathematical libraries. Right now, I am playing around with SymPy which is a computer algebra system for Python. If it wasn’t for Rod, I never would have known about it.
Anyways, I wanted to print out my first Python script. Please remember that I’m still learning and it is probably complete garbage. I ended up coding the first algorithm that I could find in my Numerical Analysis textbook which was the Bisection Method.
from sympy import * (a, b, i) = (1.0, 2.0, 1) x = symbols('x') # f(x) = x^3 + 4^2 - 10 f = x**3 + 4*x**2 - 10 FA = f.subs(x,a).evalf() while i<=1000: p = a + (b-a)/2 FP = f.subs(x,p).evalf() if FP == 0 or (b-a)/2 < .0001: print "%f %f %d" % (p, FP, i) break i = i+1 if FA*FP >0: a = p FA = FP else: b = p
I could have easily solved the problem by just calling the solve function. However, I wouldn’t have learned much about Python by doing that.
from sympy import * x = symbols('x') print [elem.evalf() for elem in solve(x**3 + 4*x**2 - 10, x)]


Comment by Rod Carvalho
Made Friday, 20 of March , 2009 at 12:17 pm
Python is quite a sexy language indeed. By the way, you wrote “SymMath” instead of “SymPy”. If you’re interested in implementing numerical methods with Python, there’s a new blog dedicated to that:
http://numericalrecipes.blogspot.com
Just curious: what code-highlighting tool did you use to generate HTML from your Python scripts? Your code snippets look rather cute.