gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:35:50 26 4
gpt4 key购买 nike

我真的刚刚开始学习如何用 Python 编写代码。我有兴趣

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

这是我的代码:

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?

我看到一些动画代码太复杂了,我看不懂。谁能帮我解决我上面提到的问题?谢谢!

最佳答案

在文件末尾执行:

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:

enter image description here

关于python绘制一维波动方程(初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26393545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com