简体   繁体   English

Python Numpy 矩阵乘法与向量收敛循环

[英]Python Numpy matrix multiplication with vector convergence loop

I need to write a code in python using numpy to iterate and loop through to multiply it a matrix by a new vector 72 times.我需要使用 numpy 在 python 中编写代码来迭代和循环以将矩阵乘以新向量 72 次。 Any help will be appreciated.任何帮助将不胜感激。

The matrix is shown as P and the vector is pop.矩阵显示为 P,向量为 pop。 As you can see, I have multiplied the matrix by the vector using B=P.dot(pop) and then I have printed B below and we get B=[135,165].如您所见,我使用 B=P.dot(pop) 将矩阵乘以向量,然后在下面打印 B,我们得到 B=[135,165]。 So what I want to do is setup a loop such that the matrix P is multiplied by B, giving a vector C.所以我想要做的是设置一个循环,使矩阵 P 乘以 B,得到一个向量 C。 And then the matrix P is multiplied by the new vector C etc etc.... and keeps going 72 times.然后将矩阵 P 乘以新的向量 C 等....并继续进行 72 次。 I know that it will converge to [100,200] and stay there, but how do I write a loop code to do this.我知道它会收敛到 [100,200] 并保持在那里,但是我该如何编写循环代码来做到这一点。

So this is what I have so far:所以这就是我到目前为止所拥有的:

import numpy as np
P=np.array([[0.8,0.1],[0.2,0.9]])
pop=([150,150])

B=P.dot(pop)

C=P.dot(B)

print B
print C

Furthermore how can I show that after each iteration, the sum is always 300 of the 2 components in the vector?此外,我如何证明每次迭代后,向量中两个分量的总和总是 300?

Thanks谢谢

This is called a power iteration for finding eigenvectors:这称为寻找特征向量的幂迭代

The for loop definitely works but it is somewhat trivial and boring:). for 循环确实有效,但它有点琐碎和无聊:)。 If you know that the series converges, as in this case, you can use a while loop with a sense of convergence to avoid unnecessary iterations.如果你知道级数收敛,比如本例,你可以使用一个有收敛感的while循环来避免不必要的迭代。

enter code here

import numpy as np
P=np.array([[0.8,0.1],[0.2,0.9]])
pop=([150,150])
B=P.dot(pop)
'''
for i in range(60):
    C=P.dot(B)
    err=np.linalg.norm(B-C,2)
    B=C
print(B)
'''
err=np.inf
iter=0
while err>10E-10:
    iter+=1
    C=P.dot(B)
    err=np.linalg.norm(B-C,2)
    B=C

print(B)
print(err)
print(iter)
> [100. 200.]
> 8.874916220860865e-10
> 67

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM