python绘制一维波动方程(初学者)

问题描述 投票:3回答:2

实际上,我刚刚开始学习如何使用Python进行编码。我有兴趣

  1. 如何再现u[x,t]矩阵。我尝试了return u,但抛出了一个错误。
  2. 如果此代码中for的循环位置正确并且可以正常运行。
  3. 最重要的是,如何在此一维波方程式上设置动画,在其中我可以看到波是如何从高斯演化成并分裂成两个相同高度的波的。

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt

dx=0.1 #space increment
dt=0.05 #time increment
tmin=0.0 #initial time
tmax=2.0 #simulate until
xmin=-5.0 #left bound
xmax=5.0 #right bound...assume packet never reaches boundary
c=1.0 #speed of sound
rsq=(c*dt/dx)**2 #appears in finite diff sol

nx = int((xmax-xmin)/dx) + 1 #number of points on x grid
nt = int((tmax-tmin)/dt) + 2 #number of points on t grid
u = np.zeros((nt,nx)) #solution to WE

#set initial pulse shape
def init_fn(x):
    val = np.exp(-(x**2)/0.25)
    if val<.001:
        return 0.0
    else:
        return val

for a in range(0,nx):
    u[0,a]=init_fn(xmin+a*dx)
    u[1,a]=u[0,a]

#simulate dynamics
for t in range(1,nt-1):
    for a in range(1,nx-1):
        u[t+1,a] = 2*(1-rsq)*u[t,a]-u[t-1,a]+rsq*(u[t,a-1]+u[t,a+1])


# Where is the code that is needed to run the simulation?  

我看到了一些动画代码,这些代码太复杂了,我无法理解。有人可以帮我解决上面提到的问题吗?谢谢!

python animation numpy matplotlib waveform
2个回答
3
投票

在文件末尾执行:

fig = plt.figure()
plts = []             # get ready to populate this list the Line artists to be plotted
plt.hold("off")
for i in range(nt):
    p, = plt.plot(u[i,:], 'k')   # this is how you'd plot a single line...
    plts.append( [p] )           # ... but save the line artist for the animation
ani = animation.ArtistAnimation(fig, plts, interval=50, repeat_delay=3000)   # run the animation
ani.save('wave.mp4')    # optionally save it to a file

plt.show()

这是mp4的gif:

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS83NXZ5Sy5naWYifQ==” alt =“在此处输入图像描述”>“ >>


0
投票

fig = plt.figure()35点= []#准备填充此列表中要绘制的线艺术家---> 36点保持(“ on”)对于范围(nt)中的i为37:38 p,= plt.plot(u [i ,:],'k')#这就是绘制单条线的方式...

© www.soinside.com 2019 - 2024. All rights reserved.