Skip to main content
 首页 » 编程设计

python之使用matplotlib.pyplot制作一维波动方程的动画

2025年05月04日9dudu

我一直在使用 python 中的 matplotlib 来显示一维波动方程的动画。但是我在制作动画时遇到了问题。我希望波的图像随时间变化。这意味着我可能需要一个循环来形成波动方程的许多不同图片。但似乎时间不能放入波函数,所以图像根本没有改变。请帮我解决我犯的错误。 以下是我写的代码:(部分代码来自《Python Scripting for Computational Science》一书)

from numpy import zeros,linspace,sin,pi 
 
import matplotlib.pyplot as mpl 
 
def I(x): 
    return sin(2*x*pi/L) 
 
def f(x,t): 
    return sin(x*t) 
 
def solver0(I,f,c,L,n,dt,tstop): 
    # f is a function of x and t, I is a function of x 
    x = linspace(0,L,n+1) 
    dx = L/float(n) 
    if dt <= 0: 
        dt = dx/float(c) 
    C2 = (c*dt/dx)**2 
    dt2 = dt*dt 
    up = zeros(n+1) 
    u = up.copy() 
    um = up.copy() 
    t = 0.0 
    for i in range(0,n): 
        u[i] = I(x[i]) 
    for i in range(1,n-1): 
        um[i] = u[i]+0.5*C2*(u[i-1] - 2*u[i] + u[i+1]) + dt2*f(x[i],t) 
    um[0] = 0 
    um[n] = 0     
    while t <= tstop: 
        t_old = t 
        t += dt 
        #update all inner points: 
        for i in range(1,n-1): 
            up[i] = -um[i] + 2*u[i] + C2*(u[i-1] - 2*u[i] + u[i+1]) + dt2*f(x[i],t_old) 
        #insert boundary conditions: 
        up[0] = 0 
        up[n] = 0 
        #update data structures for next step 
        um = u.copy() 
        u = up.copy()    
    return u 
 
c = 3.0  #given by myself 
L = 10 
n = 100 
dt = 0 
tstart = 0 
tstop = 6 
x = linspace(0,L,n+1) 
t_values = linspace(tstart,tstop,31) 
mpl.ion() 
y = solver0(I, f, c, L, n, dt, tstop) 
lines = mpl.plot(x,y) 
mpl.axis([x[0], x[-1], -1.0, 1.0]) 
mpl.xlabel('x') 
mpl.ylabel('y') 
 
counter = 0 
for t in t_values: 
    y = solver0(I,f,c,L,n,dt,tstop) 
    lines[0].set_ydata(y) 
    mpl.draw() 
    mpl.legend(['t=%4.1f' % t]) 
    mpl.savefig('sea_%04d.png' %counter) 
    counter += 1 

请您参考如下方法:

也许这就是您所需要的?

y = solver0(I,f,c,L,n,dt,t)