Professional Documents
Culture Documents
4 Exercises 97
25
20
15
10
y
5
0
5
10
40 30 20 10 0 10
x
Fig. 3.2 One realization of a random walk (N-E-S-W) with a 1000 steps. Initial and final
positions are marked in blue with a circle and a star, respectively.
3.4 Exercises
N = 5
h = np.zeros(N) # heights of family members (in meter)
h[0] = 1.60; h[1] = 1.85; h[2] = 1.75; h[3] = 1.80; h[4] = 0.50
sum = 0
i = 0
while i <= 4:
sum = sum + h[i]
i = i + 1
average = sum/N
Filename: while_instead_of_for.py.
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’)
100 3 Loops and branching
Proceed by writing the program, and then run it a few times with
different values for a and b to confirm that it works as intended. In
particular, choose combinations for a and b so that all three branches of
the if construction get tested.
Solution. The program takes two integers as input and checks if the
number a is smaller than b, equal to b, or larger than b. A message is
printed to the screen in each case.
Filename: compare_a_and_b.py.
Remarks. The program is not too robust, since it assumes the user types
an integer as input (a real number gives trouble).
r = 10.6
a = 1.3 # one side of rectangle
circle_area = m.pi*r**2
Also, print all the random numbers to the screen so that you can check
for yourself that the counting is correct. Run the program with a small
value for N (e.g., N = 10) to confirm that it works as intended.
Hint. Use random.randint(1,6) to draw a random integer between 1
and 6.
Solution. The code may be written as follows
from random import randint
We see that, in this case, 6 was drawn just a single time, so one out of
ten gives a fraction M/N of 0.1.
Filename: count_random_numbers.py.
Remarks. For large N , this program computes the probability M/N of
getting six eyes when throwing a dice.
sum as close as possible to 21, but not larger than 21. You are out of
the game if the sum passes 21.
After each draw, you are told the number and your total sum, and are
asked whether you want another draw or not. The one coming closest to
21 is the winner.
Implement this game in a program.
Hint. Use random.randint(0,10) to draw random integers in [0, 10].
Solution. The code may be written as follows
from random import randint
upper_limit = 21
not_finished = True
sum = 0
while not_finished:
next_number = randint(0, 10)
print(’You got: {:d}’.format(next_number))
sum += next_number
if sum > upper_limit:
print(’Game over, you passed 21 (with your {:d} points)!’\
.format(sum))
not_finished = False
else:
print(’Your score is now: {:d} points!’.format(sum))
answer = input(’Another draw (y/n)? ’)
if answer != ’y’:
not_finished = False
print(’Finished!’)
Filename: game_21.py.
to screen both before and after sorting. Confirm that the array has been
sorted correctly.
Solution. The code may be written as follows
import numpy as np
import random
N = 6
numbers = np.zeros(N)
From the printout, we see that the code sorts the array correctly.
Filename: sort_numbers.py.
∞
1
π=8
X
,
k=0
(4k + 1)(4k + 3)
while one form of the Euler scheme may appear as
v
u ∞
u X 1
π =t6 2
.
k=1
k
#Leibniz
sum1 = 0
for k in range(0, no_of_terms):
sum1 += 1.0/((4*k + 1)*(4*k + 3))
Leibniz_error[k] = pi - 8*sum1
sum1 *= 8
final_Leibniz_error = abs(pi - sum1)
print(’Leibniz: {:g}’.format(final_Leibniz_error))
# Euler
sum2 = 0
for k in range(1, no_of_terms+1): # Note index range
sum2 += 1.0/k**2
Euler_error[k-1] = pi - sqrt(6*sum2)
sum2 *= 6
sum2 = sqrt(sum2)
final_Euler_error = abs(pi - sum2)
print(’Euler: {:g}’.format(final_Euler_error))
plt.show()
0.7
Error with Leibniz (blue) and Euler (red)
0.6
0.5
0.4
0.3
0.2
0.1
0.0
0 20 40 60 80 100
No of terms
Fig. 3.3 Error as a function of number of terms.
We see that the scheme of Leibniz gives the least error all over the
interval. However, the difference in the error with the two schemes
becomes smaller as the number of terms increases.
Filename: compute_pi.py.