Page - 76 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 76 -
Text of the Page - 76 -
76 3 LoopsandBranching
Exercise3.9:Simple Search:Verification
Check your understandingof the search procedure inball_max_height.pyfrom
Sect.3.3.3 by comparingwhat you get “by hand” to printouts from the code. Work
on a copy ofball_max_height.py. Comment out what you do not need, and use
an arrayyof just 4 elements (or so). Fill that array with integers, so that you place
a maximum value in a certain location. Then, run through that code by hand for
everyiterationof the loop,writingdownthenumbersinlargest_height.Finally,
placeaprintcommandintheloop,so thatlargest_heightgetsprintedwithevery
iteration.Run theprogramandcompare to whatyoufoundbyhand.
Filename:simple_search_verify.py.
Exercise3.10:SortArraywithNumbers
Write a script that uses theuniform functionfromtherandommodule to generate
anarrayof6 randomnumbersbetween0and10.
The program should then sort the array so that numbers appear in increasing
order.Let theprogrammakeaformattedprintof thearray toscreenbothbeforeand
after sorting.Confirmthat the arrayhasbeensortedcorrectly.
Filename:sort_numbers.py.
Exercise3.11:Computeπ
Up through history, great minds have developed different computational schemes
for the numberπ. We will here consider two suchschemes, oneby Leibniz (1646–
1716),andonebyEuler (1707–1783).
TheschemebyLeibnizmaybe written
π =8 ∞∑
k=0 1
(4k+1)(4k+3),
whileoneformof the Euler schememayappearas
π= √√
√
√6 ∞∑
k=1 1
k2 .
If only the first N terms of each sum are used as an approximation to π, each
modifiedschemewill havecomputedπ withsomeerror.
Write a program that takes N as input from the user, and plots the error
development with both schemes as the number of iterations approaches N. Your
programshouldalso print out the final errorachievedwith bothschemes, i.e. when
the numberof terms isN. Run the programwithN = 100 and explain briefly what
thegraphsshow.
Filename:compute_pi.py.
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations – Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik