0
我想創建一個簡單的動畫,瞭解前向時間中心空間(FTCS)解決高斯速度分佈的磁通守恆方程有多糟糕(「Physics ... yeah !「)。我寫了一個基於this tutorial的小動畫。我附上了下面的代碼。我對它感到滿意(因爲我對matplotlib的動畫包沒有什麼瞭解),但是我不能讓動畫足夠慢,以便我可以看到一些東西。在Python的matplotlib動畫包中演示轉發時間中心空間
這歸結爲我不明白如何設置animation.FuncAnimation參數在代碼的最後一行。有人可以解釋,幫忙嗎?
import math
import numpy as np
import scipy as sci
import matplotlib.pyplot as plt
from matplotlib import animation
#generate velocity distribution
sigma = 1.
xZero = 0.
N = 101
x = np.linspace(-10,10,N)
uZero = 1./math.sqrt(2 * math.pi * (sigma**2)) * np.exp(-0.5*((x - xZero)/(2*sigma))**2)
v = 1
xStep = x[2]-x[1]
tStep = 0.1
alpha = v * tStep/xStep * 0.5
#include boundary conditions
u = np.hstack((0.,uZero,0.))
uNext = np.zeros(N + 2)
#solve with forward time central space and store each outer loop in data
#so it can be used in the animation
data = []
data.append(u[1:-1])
for n in range(0,100):
for i in range(1,N+1):
uNext[i] = -alpha * u[i+1] + u[i] + alpha*u[i-1]
u = uNext
data.append(u[1:-1])
data = np.array(data)
#launch up the animation
fig = plt.figure()
ax = plt.axes(xlim=(-10,10),ylim=(-1,1))
line, = ax.plot([],[],lw=2)
def init():
line.set_data([],[])
return line,
#get the data for animation from the data array
def animate(i):
y = data[i]
line.set_data(x,y)
return line,
#the actual animation
anim = animation.FuncAnimation(fig,animate,init_func=init,frames=200,interval=2000,blit=True)
plt.show()
謝謝!我把* uNext = np.zeros(N + 2)*放在外部for循環中,並修復它。 – seb
是的,就是這樣! –