我的任务是为PDE编写FTCS和Lax-Friedrich方案。以下是代码
import numpy as np
import matplotlib.pyplot as plt
N = 90
t_max = 0.5
x_min = 0
x_max = 1
dt = 0.009
v = 0.5
dx = (x_max - x_min)/N
x = np.arange(x_min, x_max + 3*dx, dx)
u_0 = np.exp(-225*(x - 0.3)**2)
u_0[np.where((x>=0.6) & (x<=0.8))] = 1.0
u_lf = u_0.copy()
u_cs = u_0.copy()
u_na = u_0.copy()
u_nb = u_0.copy()
alpha = v*dt/(2*dx)
tc = 0
for i in range(int(t_max/dt)):
plt.clf()
for j in range(N+2):
u_na[j] = (u_lf[j-1] + u_lf[j+1])/2 + alpha*(u_lf[j-1] - u_lf[j+1])
u_nb[j] = u_cs[j] + alpha*(u_cs[j-1] - u_cs[j+1])
u_lf = u_na.copy()
u_cs = u_nb.copy()
u_lf[0] = u_lf[-2]
u_lf[-1] = u_lf[1]
u_cs[0] = u_cs[-2]
u_cs[-1] = u_cs[1]
u_ex = np.exp(-225*(x - 0.3 - v*tc)**2)
u_ex[np.where((x-v*tc>=0.6) & (x-v*tc<=0.8))] = 1.0
u_ex[0] = u_ex[-2]
u_ex[-1] = u_ex[1]
plt.plot(x, u_ex, 'r', fillstyle='none', label="Exact solution")
plt.plot(x, u_lf, 'o', fillstyle='none', label="Lax-Friedrichs")
plt.plot(x, u_cs, '^', fillstyle='none', label="Central scheme")
plt.axis((0, 1, -0.5, 1.5))
plt.legend(loc=1)
plt.suptitle("Time = %1.3f" % (tc+dt))
plt.pause(0.042)
tc += dt我对u_ex不是周期性的有问题...我希望它从右边退出,从左边重新进入,就像其他两个一样。
如果有人能帮上忙那就太好了:)
编辑:
这是一张u_ex的图片,它是一个高斯函数,后面跟着一个盒子函数

发布于 2020-12-10 06:51:12
根据代码片段,您似乎正在跳过一个索引。
u_ex[0] = u_ex[-2]
u_ex[-1] = u_ex[1]第一行指示您将用倒数第二个值而不是第一个值替换第一个值。
第二行用第二个值替换最后一个值。
在覆盖之前,您可以使用一些虚拟变量来保存需要交换的数据。
last = u_ex[-1]
first = u_ex[0]
u_ex[0] = last
u_ex[-1] = firsthttps://stackoverflow.com/questions/65225707
复制相似问题