Numpy 课后习题

Numpy

Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A 2 Rn×m and B 2 Rm×m,
for n = 200, m = 500.
 

import numpy as np
from scipy.linalg import toeplitz
#建立矩阵A、B
n=200
m=500
A = np.random.randn(n,m)
B = toeplitz(range(m))
print(A)
print(B)
Exercise 9.1: Matrix operations

Calculate A + A, AAT, ATA and AB. Write a function that computes A(B - λI) for any λ.

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))

def calculate(A,B,y):
	c = B - y*np.eye(m)
	return np.dot(A,c)

y = int(input())
cal = calculate(A,B,2)
print(cal)
Exercise 9.2: Solving a linear system
Generate a vector b with m entries and solve Bx = b .
b = np.random.random(500) * 500
print(np.linalg.solve(B, b))
Exercise 9.3: Norms
Compute the Frobenius norm of A : ||A||F  and the infinity norm of B : ||B||oo  Also find the largest and
smallest singular values of
B .
norma = np.linalg.norm(A, 'fro')  
normb = np.linalg.norm(B, np.inf)  
U, S, VT = np.linalg.svd(B)
print(norma)  
print(normb)  
print(max(S))  
print(min(S))
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 time
def power_itera(A):  
    u = np.random.randint(0,10,size = n)  
    last = 1  
    lam = 0  
    num = 0  
    start = time.clock()  
    while abs(lam - last)>0.0001:  
        last = lam  
        num+=1  
        v = np.dot(A, u)  
        lam = 0  
        for vx in v:  
            if abs(lam)
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?
p_ = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]    
for p in p_:    
	C = np.random.random(size=[n, n])    
	for i in range(n):    
		for j in range(n):    
			C[i][j] = 1 if C[i][j] > p else 0
	s= np.linalg.svd(C, compute_uv=False)    
	m = np.max(s) 
print(m)
Exercise 9.6: Nearest neighbor
Write a function that takes a value z and an array A and finds the element in A that is closest to z . The
function should return the closest value, not index.
Hint: Use the built-in functionality of Numpy rather than writing code to find this value manually. In
particular, use brackets and
argmin .

def fun(A, z):  
    index = np.argmin(np.abs(A - z))  
    return A[index]







你可能感兴趣的:(Numpy 课后习题)