【问题标题】:Demonstration of Forward Time Central Space in Python's matplotlib animation packagePython的matplotlib动画包中前向时间中心空间的演示
【发布时间】:2013-05-17 11:43:02
【问题描述】:

我想制作一个简单的动画,说明前向时间中心空间 (FTCS) 在求解高斯速度分布的通量守恒方程时有多糟糕(“物理学……是的!”)。我根据this tutorial写了一个小动画。我附上了下面的代码。我对此很满意(鉴于我对 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()

【问题讨论】:

    标签: python animation matplotlib


    【解决方案1】:

    首先探索您的数据变量。如果我运行您的代码,只有 data[0] 和 data[1] 不同,从 data[1] 开始,所有数据(因此帧)都是相同的。

    np.allclose(data[1], data[100])
    True
    

    【讨论】:

    • 谢谢!我将 uNext = np.zeros(N + 2) 放在外部 for 循环中并修复它。
    猜你喜欢
    • 2015-04-24
    • 2014-03-27
    • 2020-08-30
    • 1970-01-01
    • 2021-05-08
    • 2017-02-27
    • 2011-11-14
    • 1970-01-01
    • 2021-04-02
    相关资源
    最近更新 更多