使用pip安装NumPy组件,过程如下:
1 以管理员身份打开命令提示符; 2 定位到python.exe所在目录; 3 输入python.exe-m pip install numpy; 4 等待应用下载并安装,完成后可输入python.exe -m pip list查看安装
安装完成后就可以在代码中import numpy,使用其功能了。
0. Generate matrices A, with randomGaussian entries, B, a Toeplitz matrix, where A: Rnm and B: Rmm,for n=200, m=500.
m=500
n=200
A=numpy.random.randn(n,m) #Gaussian distribution matrix
B=numpy.empty((m,m)) #Toeplitz matrix
for k in range(0,m):
rd1=numpy.random.randint(1,1024)
rd2=numpy.random.randint(1,1024)
for i in range(0,k+1):
B[i][i+m-1-k]=rd1
B[i+m-1-k][i]=rd2
1. Calculate A + A, AAT, ATA and AB. Write afunction that computes A(B-λI) for any λ.
def Func1(mA,mB,L):
X=mA.shape
for i in range(0,X[1]):
B[i][i]=B[i][i]-L
mA=mA.dot(B)
return mA
Ans=A+A
print('A+A\n',Ans)
Ans=A.dot(A.T)
print('A*AT\n',Ans)
Ans=A.T.dot(A)
print('AT*A\n',Ans)
Ans=A.dot(B)
print('A*B\n',Ans)
Ans=Func1(A,B,100)
print('Function\n',Ans)
2. Generate a vector b with m entries andsolve Bx = b.
b=numpy.random.random_integers(1,1000,50)
b=b.astype(numpy.float)
print('b\n',b)
print('x\n',numpy.linalg.solve(B,b))
3. Compute the Frobenius norm of A: ||A||Fand the infinity norm of B: ||B||∞. Also find thelargest and smallest singular values of B.
#Frobenius范数,为矩阵元素的平方和再开方
defFrobenius(Mat):
X=Mat.shape
R=0.0
for i in range(0,X[0]):
for j in range(0,X[1]):
R=R+Mat[i][j]*Mat[i][j]
R=R**0.5
return R
print(Frobenius(A))
print()
Ans=numpy.linalg.norm(B, numpy.inf) #行和范数,即矩阵行向量中绝对值之和的最大值
print(Ans,'\n')
SVD = numpy.linalg.svd(B) #奇异值分解
print('largestsingular values: ',SVD[1][0])
print('smallestsingular values: ',SVD[1][-1])
4. Generate a matrix Z, n×n, with Gaussian entries, and use the power iteration to find thelargest eigenvalue and corresponding eigenvector of Z. How many iterations areneeded till convergence?
while True:
if i!=0:
v=numpy.random.randint(1,4,n)
for i in range(0,10001):
u=Z.dot(v)
m=numpy.abs(u).max()
t=u/m
B=True
for k in range(0,n):
if abs(abs(t[k]/v[k])-1)>1.0/1048576: #收敛
B=False
break
if B==True:
break
else:
v=t.copy()
if i<10000:
print('iterations: ',i)
print('largest eigenvalue:\n',m) #最大特征值
print('corresponding eigenvector:\n',v)
break
(w,v)=numpy.linalg.eig(Z) #对比
print('comparism:\n',w)
幂乘法求解最大特征值,参考网上资料,为防止数据发散过快导致舍入误差影响,这里用了规范化迭代,使每一次迭代向量的最大分量的绝对值为1。当迭代向量前后相差不足1/1048576时,即视作收敛到目标值。这时,m即为特征根,v即为特征向量。
实际操作中,我发现特征向量经常和标准函数的结果不符,但手算验证发现迭代结果无误,这个问题有待探究。
其实有大部分情况将陷入死循环,一直得不出答案。通过查阅资料,我得知这是正常情况。存在特殊情况如:λ1=λ2,λ1=-λ2,λ无实根,λ共轭等,在这种情况下,幂迭代将不适用。而完全随机生成的数据的确容易出现以上特殊情况。
若无以上情况,迭代大多在5000次以内完成,用时不到1秒。
5. Generate an n×n matrix, denoted by C, where each entry is 1 with probability p and0 otherwise. Use the linear algebra library of Scipy to compute the singularvalues of C. What can you say about the relationship between n, p and thelargest singular value?
n=100
p=0.74
C=numpy.random.rand(n*n)
for i in range(0,n*n):
ifC[i]<p:
C[i]=1
else:
C[i]=0
C=C.reshape((n,n))
#生成矩阵
print('n=',n)
print('p=',p)
(u,s,vh)=numpy.linalg.svd(C)
print(s)
经过多次试验,我发现最大奇异值总是近似于n*p,且n越大,p越大,偏差越小。
6. Write a function that takes a value zand an array A and finds the element in A that is closest to z. The functionshould return the closest value, not index.
argmin()是求最小值索引的函数,因此即要使所求值所在位置变为最小值。可知,当|A[i]-z|最小时,A[i]即为所求,
import numpy
def Closest(A,z):
T=numpy.array(A)
T-=z
T=numpy.abs(T)
returnT.argmin()
A=numpy.random.randn(100)
z=numpy.random.rand()
print(A)
print(z)
print(A[Closest(A,z)]) #最接近的值