12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

7.6. Algorithms 672.00001024003>>> x = y>>> y = (x + a/x) / 2>>> print y2.00000000003In general we don’t know ahead of time how many steps it takes to get to the right answer, but weknow when we get there because theestimatestops changing:>>> x = y>>> y = (x + a/x) / 2>>> print y2.0>>> x = y>>> y = (x + a/x) / 2>>> print y2.0When y == x, we can stop. Here is a loop that starts with an initial estimate, x, and improves ituntil itstops changing:while True:print xy = (x + a/x) / 2if y == x:breakx = yFor most values of a this works fine, but in general it is dangerous to test float equality. Floatingpointvalues are only approximately right: most rational numbers, like 1/3, and irrational numbers,like √ 2,can’t berepresented exactly withafloat.Ratherthancheckingwhetherxandyareexactlyequal,itissafertousethebuilt-infunctionabstocompute the absolute value, or magnitude, of thedifference between them:if abs(y-x) < epsilon:breakWhereepsilonhas avalue like0.0000001that determines how closeisclose enough.Exercise 7.2 Encapsulate this loop in a function called square_root that takes a as a parameter,chooses a reasonable value ofx,and returns an estimateof thesquare root ofa.7.6 AlgorithmsNewton’s method is an example of an algorithm: it is a mechanical process for solving a categoryof problems (inthiscase, computing square roots).It is not easy to define an algorithm. It might help to start with something that is not an algorithm.When you learned to multiply single-digit numbers, you probably memorized the multiplicationtable. Ineffect, you memorized 100 specific solutions. That kind of knowledge isnot algorithmic.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!