高级编程作业 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 infinity norm of B: ||B||∞. Also find 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 find 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])

输出结果

阅读更多
个人分类: 高级编程作业
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭