# 高级编程作业 numpy 练习

Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A ∈Rn×m and B ∈Rm×m, for n = 200, m = 500.
Exercise 9.1: Matrix operations Calculate A + A, AA>,A>A and AB. Write a function that computes A(B−λI) for any λ.

import numpy as np
from scipy.linalg import toeplitz
A = np.random.random_integers(100,size = (200,500))
B = toeplitz(range(1,501),range(1,501))
print("A = ")
print(A)
print("B = ")
print(B)
print("A + A =")
print(A+A)
print("AAT = ")
print(np.dot(A,A.T))
print("ATA = ")
print(np.dot(A.T,A))
print("AB = ")
print(np.dot(A,B))

Exercise 9.2: Solving a linear system Generate a vector b with m entries and solve Bx = b.

import numpy as np
from scipy.linalg import toeplitz
b = np.random.random_integers(100,size = (500))
B = toeplitz(range(1,501),range(1,501))
print("b = ")
print(b)
print("B = ")
print(B)
x = np.linalg.solve(B,b)
print("Solution = ")
print(x)

Exercise 9.3: Norms Compute the Frobenius norm of A: ||A||F and the inﬁnity norm of B: ||B||∞. Also ﬁnd the largest and smallest singular values of B.

import numpy as np
from scipy.linalg import toeplitz
b = np.random.random_integers(100,size = (500))
A = np.random.random_integers(100,size = (200,500))
B = toeplitz(range(1,501),range(1,501))
print("||A||F = ")
print(np.linalg.norm(A,ord=2))
print("||B||∞ = ")
print(np.linalg.norm(B,ord=np.inf))
print(" the largest singular values of B =")
print(np.linalg.svd(B)[0])
print(" the smallest singular values of B =")
print(np.linalg.svd(B)[-1])


Exercise 9.4: Power iteration Generate a matrix Z, n × n, with Gaussian entries, and use the power iteration to ﬁnd the largest eigenvalue and corresponding eigenvector of Z. How many iterations are needed till convergence?
Optional: use the time.clock() method to compare computation time when varying n.

import numpy as np
from scipy.linalg import toeplitz

Z = np.random.random_integers(100,size = (200,200))
a,b = np.linalg.eig(Z)
print("the largest eigenvalue = ")
print(np.argsort(a)[0])
print("the largest corresponding eigenvector = ")
print(np.argsort(b)[0])

Exercise 9.5: Singular values Generate an n×n matrix, denoted by C, where each entry is 1 with probability p and 0 otherwise. Use the linear algebra library of Scipy to compute the singular values of C. What can you say about the relationship between n, p and the largest singular value?

import numpy as np
from scipy.linalg import toeplitz

n = 200
print("n = ",n)
C = np.zeros([n,n])
p = 0.6
print("p = ",p)
for i in range(0,200):
for j in range(0,200):
if (np.random.rand() < p):
C[i][j] = 1
print("C = ")
print(C)
x = np.linalg.svd(C)
print("the largest singular value")
print(x[0])


• 评论

• 下一篇
• 上一篇