python - 如何绘制幂迭代法近似图
问题描述
我正在尝试使用以下代码绘制前 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.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
我该如何解决这个问题,以便为我绘制一个情节?
解决方案
首先,让我告诉你,代码
while(1):
code...
break
没有意义。因为和刚才一样
code...
根据Wikipedia,您可以使用以下公式计算特征向量的下一个近似值:
轴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
然后你可以调用函数iterations = 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)
推荐阅读
- windows - 如何在 Windows 中使用绑定挂载运行 docker?
- kubernetes - Kubernetes:将应用程序部署到蓝色和绿色节点组
- python - 我需要分析数据框中的所有行并检查任何列中是否存在值
- julia - 使用广播 Julia 将向量的向量转换为矩阵
- python - 如何在 python 中旋转 Seaborn 热图?
- bash - 从 tail -f 只打印花括号之间的行
- javascript - 从 youtube api 调用中恢复 json 数据
- node.js - 获取 GCS 中文件夹的文件数和总大小的最快方法?
- r - 如何根据 r 中的唯一日期间隔形成多个子数据帧
- jcl - ibm 大型机竞赛 2020 中的 jcl 错误 jcl1 问题