Python作业—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
import random
from scipy.linalg import toeplitz

A= np.random.randn(200, 500)  # 生成一个200*500的服从正态分布(0, 1)的matrix
col=list(range(1,501))
row=list(range(1,501))
B =toeplitz(c,r)

Exercise 9.1: Matrix operations

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

#exercise 9.1
print("A+A:")
print(A+A)

print("A*A(t):")
print(np.dot(A,A.T))

print("A(t)*A:")
print(np.dot(A.T,A))

print("A*B:")
print(np.dot(A,B))
def my_func(r):
    return np.dot(A,B-R*np.ones((500,500)))

Result:






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

#exercise 9.2
b=np.random.random(500)
Bn=np.mat(B).I
result=np.dot(b,Bn)
print(result)
Result:

Exercise 9.3: Norms
Compute the Frobenius norm of A: ||A||F and the infinity norm of B: ||B||inf. Also find the largest and
smallest singular values of
B.
A2=λmax(AA)=σmax(A)

#exercise 9.3
print(np.linalg.norm(A))
print(np.linalg.norm(B,ord=np.inf))
print(np.linalg.norm(B,ord=2))
print(np.linalg.norm(B,ord=-2))

Result:


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.
选代公式 :
          Y(k) = X(k)/║ X(k)║∞
           X(k+1) = AY(k)           k=0,1,2,…             
当k充分大时,或当║ X(k)- X(k+1)║<ε时,
          Y(k)≈V1
          max  |Xj(k)| ≈ λ1                                

          1≤j≤n

import numpy as np
import numpy.linalg as LA

#exercise 9.4

#返回向量最大范数
def inf_vector_norm(array):
    return LA.norm(array,np.inf)

n=input("Input n:")
n=int(n)
A= np.random.randn(n, n) 
array=np.ones(n)
print(array)
maxElemt1=inf_vector_norm(array)
maxElemt2=inf_vector_norm(array)
flag=1
count=0
while flag or abs((maxElemt2-maxElemt1)/maxElemt1)>0.000001:
    count+=1
    maxElemt1=inf_vector_norm(array)
    for i in range(0,n):
        array[i]=array[i]/maxElemt1
    array=A*array
    maxElemt2=inf_vector_norm(array)
    flag=0
print("iteration times:"+str(count))
print("largest eigenvalue:"+str(maxElemt2))
print("corresponding eigenvector:")
print(array)

Result:

n=10:


n=100:


n=1000:

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
import random
from scipy import linalg

#exercise 9.5
npv_table=[]
for i in range(1,11,2):
    size=i
    npv_row=[]
    for p in range(1,11):
        p=p/10.0
        if random.random()>p:
            arr=[1 for x in range(0,size*size)]
        else:
            arr=[0 for x in range(0,size*size)]
        C=np.array(arr).reshape([size,size])
        v=np.max(linalg.svdvals(C))
        npv_col={}
        npv_col['v']=v
        npv_row.append(npv_col)
    npv_table.append(npv_row)
for i in range(0,5):
    for j in range(0,10):
        print('  %.3f'%npv_table[i][j]['v'],end='')
    print("")
    

Result:


n变大,v变大;p变大,v变小。

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.

import numpy as np
import random
from scipy import linalg

#exercise 9.6
def my_func(z,A):
    r=np.extract(A==z,A)
    if r.size:
        return z
    B=[abs(A[i]-z) for i in range(0,A.size)]
    index=np.argmin(B)
    return A[index]
    

#test
arr=np.arange(20)
np.random.shuffle(arr)
z=10.5
print(arr)
print(z)
print(my_func(z,arr))

Result:


猜你喜欢

转载自blog.csdn.net/qq_36755175/article/details/80376860