Python 如何绘制幂次迭代法近似图
我试图用以下代码绘制前20次迭代的特征值近似图:Python 如何绘制幂次迭代法近似图,python,python-3.x,plot,iteration,Python,Python 3.x,Plot,Iteration,我试图用以下代码绘制前20次迭代的特征值近似图: def metoda_potegowa(A,X0,iterations): iteracje=[] aproks=[] ii=0 while(1): for i in range (iterations): A = A*A x = A*X0 aproks.append(x) iteracje.append(ii) ii=ii+1 norm = np.linalg.n
def metoda_potegowa(A,X0,iterations):
iteracje=[]
aproks=[]
ii=0
while(1):
for i in range (iterations):
A = A*A
x = A*X0
aproks.append(x)
iteracje.append(ii)
ii=ii+1
norm = np.linalg.norm(x)
plt.scatter(iteracje,aproks)
plt.xlabel('iteracja')
plt.ylabel('aproksymacja')
plt.grid
plt.show
break
print (x/norm)
print (np.linalg.eig(A)[1])
我得到一个警告:
ValueError Traceback (most recent call last)
<ipython-input-96-d18eef58c53a> in <module>()
----> 1 metoda_potegowa(a,x0,5)
4 frames
/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, **kwargs)
4378 y = np.ma.ravel(y)
4379 if x.size != y.size:
-> 4380 raise ValueError("x and y must be the same size")
4381
4382 if s is None:
ValueError: x and y must be the same size
ValueError回溯(最近一次调用)
在()
---->1 metoda_potegowa(a,x0,5)
4帧
/usr/local/lib/python3.6/dist-packages/matplotlib/axes//u axes.py散点(self、x、y、s、c、marker、cmap、norm、vmin、vmax、alpha、线宽、顶点、边色、plotnonfinite、**kwargs)
4378 y=np.ma.ravel(y)
4379如果x.size!=y、 尺寸:
->4380提升值错误(“x和y必须大小相同”)
4381
4382如果s为无:
ValueError:x和y的大小必须相同
我如何修复它,以便它为我绘制一个绘图?首先,让我告诉您代码
while(1):
code...
break
没有道理。因为这和刚才一样
code...
根据,您可以使用以下公式计算特征向量的下一近似值:
轴iteracje
和aproks
对于散点图来说是不好的选择,因为我们有向量。我们如何用点来表示向量?
我们可以选择以下方法:
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
def metoda_potegowa(A,X0,iterations):
fig, ax = plt.subplots(figsize=(15,10))
b_k = X0.copy()
for i, _ in enumerate(range(iterations)):
# calculate the product between A and b_k
Ab_k = np.dot(A, b_k)
# calculate the norm
Ab_k_norm = np.linalg.norm(Ab_k)
# get next aproximation of eigenvector
b_k = Ab_k / Ab_k_norm
# plot the current iteration i
plt.scatter(list(range(1, len(b_k)+1)), b_k.ravel(), label=i)
plt.xlabel('index')
plt.ylabel('value')
# use colors to distinguish iteration
plt.legend()
plt.show()
return b_k
然后,您可以调用迭代次数=20的函数,并绘制结果:
a = np.array([[1, 0, 3], [0, 2, 0], [3, 0, 1]])
x0 = np.array([1,1,1]).transpose()
eigenvector_20 = metoda_potegowa(a,x0,20)
你用什么参数来调用这个函数?metoda_potegowa(a,x0,5),其中a=np.matrix([[1,0,3],[0,2,0],[3,0,1]);x0=np.矩阵([1,1,1]).转置();hm当我像你说的那样调用它时,它给了我一个错误:ValueError:连接轴的所有输入数组维度必须完全匹配,但是沿着维度0,索引0处的数组大小为3,索引1处的数组大小为1。你能检查一下你写的调用方法吗?函数似乎不能正常工作,这是因为我使用了np.matrix()。我需要使用np.array()。我将编辑答案。