我是 Python 的新手,我正在尝试创建一个线性卷积的小动画。
from matplotlib import pyplot as plt
from matplotlib import animation
import math
def creer_y1():
y1=[]
return y1
def update_y1(i,y1):
y1=[0,1,1,1,0]
return y1,
def creer_y2():
y2=[]
return y2
def update_y2(i,y2):
y2_stock = [0,0,0,0,0, 1,0,0,0,0, 1,1,0,0,0, 1,1,1,0,0 ,0,1,1,1,0 ,0,0,1,1,1 ,0,0,0,1,1 ,0,0,0,0,1, 0,0,0,0,0]
y2 = y2_stock[0+5*i:5+5*i]
print(y2)
return y2,
def creer_convo():
convo=[]
return convo
def update_convo(i,y1,y2,convo):
convo[i]=y1[0]*y2[0]+y1[1]*y2[1]+y1[2]*y2[2]+y1[3]*y2[3]+y1[4]*y2[4]
print(convo)
return convo,
def create_animation():
fig = plt.gcf()
ax = plt.axes(xlim=(0,10), ylim=(0,2))
ax.set_aspect('equal')
y1=creer_y1()
y2 = creer_y2()
convo=creer_convo()
anim1 = animation.FuncAnimation(fig,update_y1,fargs=(y1,),frames=9,interval=1000)
anim2 = animation.FuncAnimation(fig,update_y2,fargs=(y2,),frames=9,interval=1000)
anim_convo = animation.FuncAnimation(fig,update_convo,fargs=(y1,y2,convo,),frames=9,interval=1000)
plt.title('Linear Convolution Animation')
plt.show()
if __name__=='__main__':
create_animation()
错误消息如下:
convo[i]=y1[0]*y2[0]+y1[1]*y2[1]+y1[2]*y2[2]+y1[3]*y2[3]+y1[4]*y2[4]
IndexError: list index out of range
我想这是因为当我尝试通过 animation_convo 调用 update_convo 时,它会将 y1 和 y2 的未更新版本传递给 update_convo。
我试图研究如何处理它,其中一个解决方案似乎是使用模块 ctypes 以便在 Python 中使用某种指针。但是,我认为这在我的情况下有点矫枉过正,我想知道他们是否有任何方法可以将对 y1 和 y2 的 PyObject 的引用传递给我的函数 update_convo。
我希望我的问题足够清楚,我会非常感谢任何帮助我或给我信息的人。