优化这段代码:import numpy as np import matplotlib.pyplot as plt from ipywidgets import interact, interactive, fixed # 定义模型参数 c = 1.0 # 平流速度 L = 130.0 # 空间范围 T = 40.0 # 时间范围 dx = 1 # 空间步长 dt = 0.05 # 时间步长 # 定义空间和时间的网格 xgrid = np.arange(-30.0, 100.0+dx, dx) tgrid = np.arange(0.0, T+dt, dt) # 定义初始条件 u0 = np.zeros_like(xgrid) u0[(xgrid >= -10.0) & (xgrid <= 10.0)] = 20.0 # 定义边界条件 def bc(u, t): u[0] = u[-1] return u # 定义迎风格式 def upwind(u, dx, dt, c): unew = u.copy() for i in range(1, len(u)): if c > 0: unew[i] = u[i] - cdt/dx(u[i] - u[i-1]) else: unew[i] = u[i] - cdt/dx(u[i+1] - u[i]) return unew # 计算数值解 u = u0.copy() for n in range(len(tgrid)-1): u = bc(u, tgrid[n]) u = upwind(u, dx, dt, c) # 绘制数值解 def plot_numerical_solution(t): n = int(t/dt) plt.plot(xgrid, u0, 'b--', label='Initial Condition') plt.plot(xgrid, u, 'r-', label='Numerical Solution') plt.title('Numerical Solution at t = {:.2f}'.format(tgrid[n])) plt.xlabel('x') plt.ylabel('u') plt.legend() plt.show(),优化后能有下一个时刻的数值解曲线
时间: 2024-03-30 14:34:31 浏览: 333
Matplotlib.pyplot 三维绘图的实现示例
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact
# 定义模型参数
c = 1.0 # 平流速度
L = 130.0 # 空间范围
T = 40.0 # 时间范围
dx = 1 # 空间步长
dt = 0.05 # 时间步长
# 定义空间和时间的网格
xgrid = np.arange(-30.0, 100.0+dx, dx)
tgrid = np.arange(0.0, T+dt, dt)
# 定义初始条件
u0 = np.zeros_like(xgrid)
u0[(xgrid >= -10.0) & (xgrid <= 10.0)] = 20.0
# 定义边界条件
def bc(u):
u[0] = u[-1]
return u
# 定义迎风格式
def upwind(u, dx, dt, c):
unew = np.zeros_like(u)
if c > 0:
unew[0] = u[0]
unew[1:] = u[1:] - c * dt / dx * (u[1:] - u[:-1])
else:
unew[-1] = u[-1]
unew[:-1] = u[:-1] - c * dt / dx * (u[1:] - u[:-1])
return unew
# 计算数值解
u = u0.copy()
for n in range(len(tgrid)-1):
u = bc(u)
u = upwind(u, dx, dt, c)
# 绘制数值解
def plot_numerical_solution(t):
n = int(t/dt)
plt.plot(xgrid, u0, 'b--', label='Initial Condition')
plt.plot(xgrid, u, 'r-', label='Numerical Solution')
plt.title('Numerical Solution at t = {:.2f}'.format(tgrid[n]))
plt.xlabel('x')
plt.ylabel('u')
plt.legend()
plt.show()
# 使用ipywidgets交互式绘制图像
interact(plot_numerical_solution, t=(0.0, T, dt))
阅读全文