Solutions to exercises

4.7. Solutions to exercises#

Exercise 4.1

a = np.array([1,2,3,4,5,6,7,8,9,10,11,32,55,78,22,99,55,33.2,55.77,99,101.3])

#some code to set the first three and last two entries to zero 

# A bit tricky, but these work
a[0] = 0
a[1] = 0
a[2] = 0

# We could count forwards (a[19] = 0 and a[20] = 0), but is much 
# easier to count backwards from the  end
a[-2] = 0
a[-1] = 0
print(a)

Exercise 4.2:

a = np.array(range(20))+1
print(a)
a[0:10]  =  0
print(a)

Exercise 4.2\(*\):

a = np.array([1,2,3,4,5,6,7,8,9,10,11,32,55,78,22,99,55,33.2,55.77,99,101.3])
a[-2:]=0
a[:2]=0
print(a)

Exercise 4.3:

n = np.array(range(21))
out = 2**n
print(out)

Exercise 4.4:

a = np.linspace(-2,1,20)
print(a)

Exercise 4.5:

a = np.arange(60,49.9,-0.5)
print(a)

Exercise 4.6:

raw = np.random.normal(7.5,1,300)
rounded_grades = np.round(raw*2)/2
print(rounded_grades)

Exercise 4.7:

import matplotlib.pyplot as plt
bins = np.arange(np.min(rounded_grades),np.max(rounded_grades)+0.5,0.5)

plt.figure()
plt.hist(rounded_grades, bins=bins)
plt.xlabel('Grade')
plt.ylabel('#')
plt.show()

Exercise 4.8:

m1 = np.zeros([3,3])
m1[0,:] = np.array([1,1,0])
m1[1,:] = np.array([0,2,1]) 
m1[2,:] = np.array([1,0,1]) 
m2 = np.zeros([3,3])
m2[:,0] = np.array([1,3,1])
m2[:,1] = np.array([3,1,1]) 
m2[:,2] = np.array([0,1,1]) 

# Check the matrices  
print(m1)
print()
print(m2)
print()

product = np.matmul(m1,m2)
print(product)

Exercise 4.9:

import numpy as np
import matplotlib.pyplot as plt

measurements = np.random.normal(5,1,20)
print(measurements)

average_n = np.cumsum(measurements)/np.arange(1,len(measurements)+1)

plt.figure()
plt.plot(np.arange(1,len(measurements)+1), average_n)
plt.xlabel('n')
plt.ylabel('average')
plt.show()

Exercise 4.10:

import numpy as np

array_skip = np.arange(14,44,2)
print(array_skip)


x = np.linspace(0,4,20)
y = np.sqrt(x)
print(y)

Excercise 4.11

import matplotlib.pyplot as plt

#First we define our function
def f(x):
    return np.exp(x**2)

x = np.linspace(0,1,1000)         #generate an array with x values

#make the figure
plt.figure(figsize=(6,4))
plt.plot(x,f(x))
plt.xlim(0,1)
plt.ylim(0)
plt.ylabel('f(x)')
plt.xlabel('x')
plt.show()

print('Maximum value of f(x) in the interval [0,1] is %.3f' %(np.max(f(x))))

The area under the graph is roughly equal to half of the total area of the square 1x3, i.e. 1.5.

Exercise 4.12

N = int(1e6)   #number of points that we are going to use in our calculation
x_a = 0
x_b = 1
y_a = 0
y_b = 3
#Generating our samples:
random_x = np.random.uniform(x_a,x_b,size=N)   
random_y = np.random.uniform(y_a,y_b,size=N)

Exercise 4.13

from time import time

t1 = time()

s = 0

for i in range(len(random_x)):
    if random_y[i] <= np.exp(random_x[i]**2):
        s+= 1

solution_integral = (x_b-x_a)*(y_b-y_a)*s/N

print('The solution of the integral is %.6f' %(solution_integral))            
print('Time for calculation: %.3f s' %(time()-t1))

Exercise 4.14

t1 = time()

s = np.sum(random_y <= np.exp(random_x**2))

solution_integral = 3*s/N

print('The solution of the integral is %.6f' %(solution_integral))            
print('Time for calculation: %.3f s' %(time()-t1))

Exercise 4.15

random_x = np.random.uniform(0,1,1000)
random_y = np.random.uniform(0,3,1000)

points_within_area = np.array([random_x[random_y <= np.exp(random_x**2)],random_y[random_y <= np.exp(random_x**2)]])
points_outside_area = np.array([random_x[random_y > np.exp(random_x**2)],random_y[random_y > np.exp(random_x**2)]])

plt.figure(figsize=(6,4))
plt.plot(points_outside_area[0],points_outside_area[1], '.',c='red')
plt.plot(points_within_area[0],points_within_area[1], '.', c='green')
plt.plot(x,f(x),linewidth=3,label='f(x)')
plt.xlim(0,1)
plt.ylim(0,3)
plt.ylabel('f(x)')
plt.xlabel('x')
plt.legend()
plt.show()

Exercise 4.16

def moving_avg(p, k):
    
    F = np.empty(len(p)-(k-1))
    
    for i in range(len(p)-(k-1)):
        F[i] = (1/k)*np.sum(p[i:i+k])
        
    return F

Z = np.arange(4,20)
print(Z)
print(moving_average(Z, 3))