Learning Python

March 20th, 2009

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.

Comment by eldila

Made Friday, 20 of March , 2009 at 1:42 pm

Thanks for catching that error for me. I guess that is what happens when you don’t proof-read. Also, thanks for sending me the link. I am going to subscribe to it.

As for the code highlighting, I am using a wordpress plugin called WP-Syntax. In addition, I added the following css:

pre {
   background-color:#EBEBEB;
   border:thin solid #B5B5B5;
   line-height:1;
   margin:5px;
   padding:15px;
}

Comment by Rod Carvalho

Made Friday, 20 of March , 2009 at 2:29 pm

Thanks for the info. I asked about the code-highlighting feature because I don’t like Wordpress’ built-in highlighter. However, as my blog is hosted by Wordpress, I can’t use plug-ins. Oh well…

BTW, this book might interest you (you can preview it):
http://books.google.com/books?id=WiDie-hev1kC

Comment by eldila

Made Friday, 20 of March , 2009 at 5:12 pm

Cool, I skimmed through the book and it looks really interesting. I might have to get it the next time go book shopping :D

Leave a Reply