【问题标题】:python graphing the 1D wave equation (Beginner)python绘制一维波动方程(初学者)
【发布时间】:2014-10-15 23:01:29
【问题描述】:

我刚刚开始学习如何用 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 的说明:您不应该在 Python 中的代码行末尾添加分号。尽管它们在技术上是允许的,但它们完全是多余的,而且更难于阅读,因为行尾的分号(表示什么都没有)看起来像行尾的冒号(这表明以下代码是内部块的一部分。)我已经编辑了您的代码以删除那些不必要的分号,并且我还进行了其他小的更改以清理您的代码。
  • 我不确定numpy 是否带有图形库(我个人从未使用过它)。可能有,但如果没有,您可能需要使用Tkinterwiki.python.org/moin/TkInter

标签: python animation numpy matplotlib waveform


【解决方案1】:

在你的文件末尾做:

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:

【讨论】:

  • 函数def init_fn(x):,请问是什么?是初始条件?方程是如何积分的?
  • @Alex:函数init_fx 是一个以 x=0 为中心的单个凹凸。凹凸的具体形式exp(-x**2/s) 通常称为高斯曲线或钟形曲线。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多