9.1
import numpy as np
from scipy.linalg import toeplitz
import random
n=200
m=500
A=np.random.normal(size=(n,m))
row=np.random.random(m)
col=np.random.random(m)
B=toeplitz(row,col)
#exercise 9.1
print(A+A)
print(np.dot(A,A.T))
print(np.dot(A.T,A))
print(np.dot(A,B))
def func1(c):
return np.dot(A,B - c * np.ones((m,m)))
9.2
#exercise 9.2
b=np.random.random(m)
B_inverse=np.mat(B).I
x=np.dot(b,B_inverse)
print(x)
9.3
#exercise 9.3
print(np.linalg.norm(A))
print(np.linalg.norm(B,np.inf))
print(np.linalg.norm(B,-2))#smallest
print(np.linalg.norm(B,2))#biggest
9.4
import numpy as np
Z=np.random.normal(size=(200,200))
print(Z)
def eigenvalue(A, v):
Av = A.dot(v)
return v.dot(Av)
def power_iteration(A):
n, d = A.shape
v = np.ones(d) / np.sqrt(d)
ev = eigenvalue(A, v)
iter_count=0
while True:
Av = A.dot(v)
v_new = Av / np.linalg.norm(Av)
ev_new = eigenvalue(A, v_new)
if np.abs(ev - ev_new) < 0.01:
break
v = v_new
ev = ev_new
iter_count+=1
return ev_new, v_new, iter_count
print(power_iteration(Z))
9.5
#exercise 9.5
p=random.random()
C=np.random.binomial(1,p,size=(n,n))
print(np.linalg.norm(C,2))
9.6
import numpy as np
last_smallest=-100
def func2(z,A):
global last_smallest
n, d= A.shape
A_=np.reshape(A,(1,n*d))
A_[0].sort()
smallest=np.argmin(A_)
if A_[0][smallest]>=z:
if abs(A_[0][smallest]-z)<=abs(last_smallest-z):
return A_[0][smallest]
else:
return last_smallest
elif n*d==1:
return A_[0][smallest]
else:
last_smallest=A_[0][smallest]
return func2(z,A_[:,1:])
A=np.array([[3,4,5,8,7,9,1,16,6,10,13]])
print(func2(11.5,A))