12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

7.9. Exercises 69decrement: An update that decreases the value of avariable.iteration: Repeatedexecutionofasetofstatementsusingeitherarecursivefunctioncalloraloop.infinite loop: A loop inwhich theterminating condition isnever satisfied.7.9 ExercisesExercise7.3 Totestthesquarerootalgorithminthischapter,youcouldcompareitwithmath.sqrt.Writeafunction namedtest_square_rootthat prints atablelikethis:1.0 1.0 1.0 0.02.0 1.41421356237 1.41421356237 2.22044604925e-163.0 1.73205080757 1.73205080757 0.04.0 2.0 2.0 0.05.0 2.2360679775 2.2360679775 0.06.0 2.44948974278 2.44948974278 0.07.0 2.64575131106 2.64575131106 0.08.0 2.82842712475 2.82842712475 4.4408920985e-169.0 3.0 3.0 0.0Thefirstcolumnisanumber,a;thesecondcolumnisthesquarerootofacomputedwiththefunctionfrom Exercise 7.2; the third column is the square root computed by math.sqrt; the fourth columnistheabsolute value of the difference between the twoestimates.Exercise 7.4 The built-in functioneval takes a string and evaluates it using the <strong>Python</strong> interpreter.For example:>>> eval('1 + 2 * 3')7>>> import math>>> eval('math.sqrt(5)')2.2360679774997898>>> eval('type(math.pi)')Write a function called eval_loop that iteratively prompts the user, takes the resulting input andevaluates it usingeval,and printsthe result.It should continue until the user enters 'done', and then return the value of the last expression itevaluated.Exercise7.5 ThebrilliantmathematicianSrinivasaRamanujanfoundaninfiniteseries 2 thatcanbeused togenerate anumerical approximation of π:2 Seewikipedia.org/wiki/Pi.1π = 2√ 29801∞∑k=0(4k)!(1103+26390k)(k!) 4 396 4k

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

Saved successfully!

Ooh no, something went wrong!