Page - 49 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 49 -
Text of the Page - 49 -
2.7 Exercises 49
c) Generate all the combinations of throwing two dice (the number of eyes can
vary from1 to 6). Count howmany combinationswhere the sumof the eyes
equals7.
Filename:combine_sets.py.
Exercise2.13: Frequencyofrandomnumbers
Writeaprogramthat takes apositive integerN as input and thendrawsN random
integers in the interval Ε1;6 (bothends inclusive). In theprogram,counthowmany
of thenumbers,M, that equal6andwriteout the fractionM=N .Also,print all the
randomnumbers to the screen so that youcan check foryourself that the counting
is correct. Run theprogramwith a small value forN (e.g.,N = 10) to confirm that
itworksas intended.
Hint Userandom.randint(1,6) todrawarandomintegerbetween1and6.
Filename:count_random_numbers.py.
Remarks For largeN , this programcomputes theprobabilityM=N of getting six
eyeswhen throwingadie.
Exercise2.14:Game21
Consider some game where each participant draws a series of random integers
evenlydistributed from0and10,with the aimof getting the sumas close as pos-
sible to 21, but not larger than 21. You are out of the game if the sumpasses 21.
Aftereachdraw,youare told thenumberandyour total sum,andareaskedwhether
youwantanotherdrawornot. Theonecomingclosest to21 is thewinner.
Implement thisgameinaprogram.
Hint Userandom.randint(0,10) todrawrandomintegers in Ε0;10 .
Filename:game_21.py.
Exercise2.15:Linear interpolation
Somemeasurementsyi, i D 0;1;:: :;N (givenbelow), of a quantityy havebeen
collected regularly, once everyminute, at times ti D i, i D 0;1;:: :;N . Wewant
tofind thevaluey in between themeasurements, e.g., at t D 3:2min. Computing
suchy values is called interpolation.
Letyourprogramuse linearinterpolation tocomputeybetweentwoconsecutive
measurements:
1. Find i such that ti t tiC1.
2. Findamathematical expressionfor thestraight line thatgoes through thepoints
.i;yi/and .iC1;yiC1/.
3. Compute they valueby inserting theuserβs timevalue in theexpression for the
straight line.
a) Implement the linear interpolation technique in a function that takes an array
with theyi measurements as input, togetherwith some time t, and returns the
interpolatedy valueat time t.
back to the
book Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python"
Programming for Computations β Python
A Gentle Introduction to Numerical Simulations with Python
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2016
- Language
- English
- License
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 248
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik