元素生成:
import numpy as np
from scipy.linalg import toeplitz
import time
mu,sigma = 0, 1.0
n,m = 200, 500
A = np.random.normal(loc = mu, scale = sigma, size = (n,m))
C = [a for a in range(1, m + 1)]
B = toeplitz(C,C)
9.1
print(A + A)
print(np.dot(A, A.T))
print(np.dot(A.T, A))
print(np.dot(A, B))
C = B - lamda * (np.eye(m))
print(np.dot(A, C))
9.2
b = np.ones((m, 1))
x = np.linalg.solve(B, b)
print(x)
9.3
A_F = np.linalg.norm(A, 'fro')
print("the Frobenius norm:", A_F)
B_F = np.linalg.norm(B, np.inf)
print("the infinity norm:", B_F)
lar_sin = np.linalg.norm(B, 2)
smal_sin = np.linalg.norm(B, -2)
print("the largest singular:", lar_sin)
print("the smallest singular:", smal_sin)
9.4
Z = np.random.standard_normal((n, n))
num = 0
u_k = np.ones(n)
v_k_norm = 0
v_k = np.zeros(n)
begin = time.clock()
while (True):
v_k = np.dot(Z, u_k)
v_k_norm_temp = v_k_norm
v_k_norm = np.linalg.norm(v_k)
u_k = v_k / v_k_norm
num += 1
if (abs(v_k_norm_temp - v_k_norm) < 0.0005):
break;
end = time.clock()
print("the largest eigenvalue:", v_k_norm)
print("the corresponding eigenvector:", u_k)
print("The number of iterations:", num)
print("computation time when varying n:", end - begin)
9.5
p = 0.5
C = np.random.binomial(1, p, (n, n))
lar_sin = np.linalg.norm(C, 2)
smal_sin = np.linalg.norm(C, -2)
print("the smallest singular:", smal_sin)
print("the largest singular:", lar_sin)
print("n * p:", n * p)
print("the largest singular is closed with n * p \nso that we can say they are equal!")
9.6
def fun_closest(A, z):
B, C = A[A > z], A[A <= z]
ceil, floor = 0, 0
if (len(B)):
ceil = np.argmin(B)
else:
return C[np.argmax(C)]
if (len(C)):
floor = np.argmax(C)
else:
return B[ceil]
if (abs(B[ceil] - z) < abs(C[floor] - z)):
return B[ceil]
else:
return C[floor]
z = -5
closest = fun_closest(A, z)
print("the closest value:", closest)