一维线性时间与空间平流方程数值解法python
时间: 2023-08-08 21:04:34 浏览: 47
非常抱歉,我刚才理解错了你的问题。以下是一维线性时间与空间平流方程的数值解法Python代码示例:
## 显式欧拉法
import numpy as np
import matplotlib.pyplot as plt
nx = 101 # 空间节点数
nt = 100 # 时间节点数
dx = 2 / (nx - 1) # 空间步长
dt = 0.01 # 时间步长
c = 1 # 平流速度
u = np.ones(nx) # 定义初始条件,u=1
u[int(0.5 / dx):int(1 / dx + 1)] = 2 # 在0.5<=x<=1之间设置u=2
un = np.ones(nx) # 定义数组un,用于保存上一步的u值
for n in range(nt):
un = u.copy() # 将当前u值保存在un数组中
for i in range(1, nx): # 计算下一时刻的u值
u[i] = un[i] - c * dt / dx * (un[i] - un[i - 1]) # 显式欧拉法
plt.plot(np.linspace(0, 2, nx), u) # 绘制数值解
plt.show()
## Lax-Wendroff方法
import numpy as np
import matplotlib.pyplot as plt
nx = 101 # 空间节点数
nt = 100 # 时间节点数
dx = 2 / (nx - 1) # 空间步长
dt = 0.01 # 时间步长
c = 1 # 平流速度
u = np.ones(nx) # 定义初始条件,u=1
u[int(0.5 / dx):int(1 / dx + 1)] = 2 # 在0.5<=x<=1之间设置u=2
un = np.ones(nx) # 定义数组un,用于保存上一步的u值
for n in range(nt):
un = u.copy() # 将当前u值保存在un数组中
u[1:-1] = un[1:-1] - c * dt / dx * (un[2:] - un[:-2]) + \
c**2 * dt**2 / (2*dx**2) * (un[2:] - 2*un[1:-1] + un[:-2]) # Lax-Wendroff方法
plt.plot(np.linspace(0, 2, nx), u) # 绘制数值解
plt.show()