【第十一周】numpy作业

本文通过多个练习,演示了如何使用Python的NumPy和SciPy库进行矩阵运算,包括矩阵加法、乘法、求逆、解线性方程组、计算范数及奇异值分解等,并实现了幂迭代法寻找最大特征值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A is n*m matrix and B is m*m matrix, for n=200, m=500.

Exercise 9.1:Matrix operation

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

from scipy.linalg import toeplitz
import numpy as np


###简化200*500 为20*50
###A = np.random.randn(200,500)
###B = toeplitz(list(range(1,501))

def ex_one(A,B,c):
             print("Matrix A:\n",A)
             print("Starting to compute.......")
             print("Matrix A+A:\n",A+A)
             print("Matrix A.At:\n",A@A.T)
             print("Matrix At.A:\n",A.T@A)
             print("Matrix A.B:\n",A@B)
             
             print("Matrix A.(B-c*I):\n",A@(B-c*np.eye(50)))
A = np.random.randn(20,50)
B = toeplitz(list(range(1,51)))
ex_one(A,B,2)

运行截图(部分):



Exercise 9.2:Solving a linear system

Generate a vector b with m entries and solve Bx=b.

from scipy.linalg import toeplitz
import numpy as np

###简化200*500 为20*50
###A = np.random.randn(200,500)
###B = toeplitz(list(range(1,501))


def ex_two(B,b):
    print("Bx=b solving for x....")
    print(np.linalg.solve(B,b))
    
A = np.random.randn(20,50)
B = toeplitz(list(range(1,51)))
b = np.array(list(range(1,51)))
ex_two(B,b)

运行截图:



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.

from scipy.linalg import toeplitz
import numpy as np

###简化200*500 为20*50
###A = np.random.randn(200,500)
###B = toeplitz(list(range(1,501))


def ex_three(A,B):
    print("The Frobenius norm of A:",np.linalg.norm(A))
    print("The infinity norm of B:",np.linalg.norm(B,np.inf))
    u,s,vh=np.linalg.svd(B)
    print("Max singular value:",max(s))
    print("Min singular value:",min(s))
    
A = np.random.randn(20,50)
B = toeplitz(list(range(1,51)))
b = np.array(list(range(1,51)))
ex_three(A,B)

运行截图:



Exercise 9.4: Power iteration

Generate a matrix Z× 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. 


from scipy.linalg import toeplitz
import numpy as np
import random
import time

###简化200*500 为20*50
###A = np.random.randn(200,500)
###B = toeplitz(list(range(1,501))


def ex_four(A):
    begin = time.clock()
    esp = 0.000001
    count = 0
    
    b_k = np.random.rand(A.shape[1])
    a1=8
    a2=1
    
    while( abs(a2-a1)>esp ):
       b_k1 = np.dot(A,b_k)
       a1 = np.linalg.norm(b_k)
       
       b_k = b_k1/a1
       a2 = np.linalg.norm(b_k)
       
       count +=1

    end = time.clock()
    print(A)
    print("Iteration times:",count)
    print("time:",end-begin)
    
A = np.random.randn(20,20)
ex_four(A)

运行截图:



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

from scipy.linalg import toeplitz
import numpy as np
import random

###简化200*500 为20*50
###A = np.random.randn(200,500)
###B = toeplitz(list(range(1,501))


def ex_five(n,p):
    x = []
    for i in range(0,n):
        x.append([])
        for j in range(0,n):
           r=random.random()
           if(p<r):
             x[i].append(1)
           else:
             x[i].append(0)
    C = np.array(x)
    print("C is:\n",C)
    u,s,vh=np.linalg.svd(C)
    print("Max singular value:",max(s))


n=input("n=")
p=input("p=")
ex_five(int(n),float(p))

运行截图:


由不同的n、p输入,发现当n变大,p变小时max sigular value变大。

Exercise 9.6: Nearest neighbor
Write a function that takes a value and an array and finds the element in 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. 

from scipy.linalg import toeplitz
import numpy as np

###简化200*500 为20*50
###A = np.random.randn(200,500)
###B = toeplitz(list(range(1,501))


def ex_six(A,z):
    sub = [abs(A[i]-z) for i in range(0,A.size)]
    s=np.argmin(sub)
    return A[s]
    
A = np.random.randn(20,50)
B = toeplitz(list(range(1,51)))
b = np.array(list(range(1,51)))
C = np.array([1,2,3,4,7,8,9])
print("closest value:",ex_six(C,5))

运行截图:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值