代码:
import numpy import time from scipy import linalg n = 200 m = 500 A = numpy.random.normal(size = (n, m)) f = numpy.random.randint(1, 1000, size = m) B = linalg.toeplitz(f) #9.1 #A+A A_A = A + A '''print(A_A)''' #AAT AAT = numpy.dot(A, A.T) '''print(AAT)''' #ATA ATA = numpy.dot(A.T, A) '''print(ATA)''' #AB AB = numpy.dot(A, B) '''print(AB)''' #计算A(B-sI) def func1(A, B, s): I = numpy.eye(B.shape[0]) return numpy.dot(A, B-s*I) s = 3 result = func1(A, B, s) '''print(result)''' #9.2 b = numpy.random.random(size = m) * 10 #求解线性方程Bx = b def solve(B, b): return numpy.linalg.solve(B, b) x = solve(B, b) '''print(x)''' #9.3 def FA(A): return numpy.linalg.norm(A, "fro") #the Frobenius norm of A: FofA = FA(A) '''print(FofA)''' #the infinity norm of B def IB(B): return numpy.linalg.norm(B, numpy.inf) IofB = IB(B) '''print(IofB)''' #singular values U, sigma, V = numpy.linalg.svd(B) maxSV = max(sigma) minSV = min(sigma) '''print(maxSV) print(minSV)''' #9.4 #求Z的特征值和特征向量 Z = numpy.random.normal(size = (n, n)) #eigenvalue和eigenvecor def maxabs(x): k = 1 for i in range(len(x)): if abs(x[i]) > abs(x[k]): k = i return abs(x[k]) def max_eigen(x0, Z, eps): count = 0 x1 = x0 y = x1/maxabs(x1) x0 = numpy.dot(Z, x0) count += 1 while abs(maxabs(x1) - maxabs(x0)) > eps and count < 10000: x1 = x0 y = x1/maxabs(x1) x0 = numpy.dot(Z, y) count += 1 return maxabs(x1), y, count x0 = numpy.ones(n) eps = 0.001 t = time.clock() e_value1, e_vector1, count = max_eigen(x0, Z, eps) t = time.clock() - t '''print(e_value1) print(e_vector1) print(count) print(t)''' #9.5 C = numpy.zeros((n,n)) p = 0.8 count = 0 for i in range(n): for j in range(n): if numpy.random.rand() < p: C[i,j] = 1 count += 1 '''print(C)''' '''print(count)''' p = count/(n*n) U1, sigma1, V1 = numpy.linalg.svd(C) maxSV1 = max(sigma1) '''print(n) print(p) print(maxSV1) print(n*p)''' #观察并计算可见maxSV1等于n*p #9.6 z = 400 arr = numpy.random.randint(1, 1000, size = n) def nearest(arr, z): arr = arr.reshape(arr.size) cmp_arr = abs(arr - z) return arr[numpy.argmin(cmp_arr)] nearest_value = nearest(arr, z) '''print(nearest_value)'''