Seite - 75 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 75 -
Text der Seite - 75 -
3.4 Exercises 75
if a < b:
print(’\na is the smallest of the two numbers’)
elif a == b:
print(’\na and b are equal’)
else:
print(’\na is the largest of the two numbers’)
Proceedbywriting theprogram,andthenrunit a fewtimeswithdifferentvalues
fora andb to confirmthat it worksas intended. In particular, choosecombinations
foraandb so thatall threebranchesof theifconstructionget tested.
Filename:compare_a_and_b.py.
Remarks Theprogramisnot too robust, since it assumes the user typesan integer
as input (a realnumbergives trouble).
Exercise3.6:AreaofRectangleVersusCircle
Consider one circle and one rectangle. The circle has a radius r = 10.6. The
rectangle has sides a and b, but only a is known from the outset. Let a = 1.3
andwriteaprogramthatusesawhile looptofindthe largestpossible integerb that
givesa rectangleareasmaller than,butascloseaspossible to, theareaof thecircle.
Run theprogramandconfirmthat it gives the rightanswer (which isb=271).
Filename:area_rectangle_vs_circle.py.
Exercise3.7:FrequencyofRandomNumbers
Write a programthat takes a positive integerN as input and then drawsN random
integers from the interval [1,6]. In the program, count how many of the numbers,
M, that equal6andprintout the fractionM/N. Also,printall the randomnumbers
to thescreenso thatyoucancheckforyourself that thecounting iscorrect.Run the
programwithasmallvalueforN (e.g.,N = 10) toconfirmthat itworksas intended.
Hint Userandom.randint(1,6) todrawa randomintegerbetween1and6.
Filename:count_random_numbers.py.
Remarks For largeN, this programcomputes the probabilityM/N of getting six
eyeswhen throwingadice.
Exercise3.8:Game21
Consider some game where each participant draws a series of random integers
evenly distributed between 0 and 10, with the aim of getting the sum as close as
possible to21,butnot larger than21.Youareoutof thegameif thesumpasses21.
After each draw, you are told the number and your total sum, and are asked
whetheryouwantanotherdrawornot.Theonecomingclosest to21 is the winner.
Implement thisgamein aprogram.
Hint Userandom.randint(0,10) to drawrandomintegers in [0,10].
Filename:game_21.py.
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Band
- Second Edition
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2020
- Sprache
- englisch
- Lizenz
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 356
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik