import numpy as np import matplotlib.pyplot as plt # 设置模拟参数 D = 0.12# 热扩散率 L = 20 # 模拟深度 T = 365 * 10 # 模拟时间 h = 0.1 # 栅格大小 dt = 0.01 # 时间步长 N = int(T / dt) # 时间步数 M = int(L / h) + 1 # 深度格点数 K = int(T / 90) # 画图次数 # 初始化温度分布 T0 = np.ones(M) * 10 T0[0] = 10 + 12 # 表面温度 T0[-1] = 11 # 深度为20米处温度 # 初始化温度矩阵 T = np.zeros((M, N)) T[:, 0] = T0 # 进行数值求解 for n in range(1, N): for i in range(1, M - 1): T[i, n] = T[i, n-1] + D * dt / h**2 * (T[i+1, n-1] - 2*T[i, n-1] + T[i-1, n-1]) # 边界条件 if T.all()!=0: T[0, n] ==10 + 12 * np.sin(2 * np.pi * n * dt / T) and T[-1, n] ==11 else: break # 每隔90天画一次图 if n % int(T / 4) == 0: plt.plot(T[:, n], np.linspace(0, L, M), label=f'{n*dt/365:.0f} year') plt.legend() # 显示温度轮廓图 plt.xlabel('Temperature (°C)') plt.ylabel('Depth (m)') plt.title('Temperature Profile') plt.gca().invert_yaxis() plt.show()为什么这个代码画不出图
时间: 2024-03-23 09:37:14 浏览: 127
这个代码有两个问题:
1. 在边界条件的处理中,应该使用赋值操作`=`而不是相等比较操作`==`。因此需要将 `T[0, n] ==10 + 12 * np.sin(2 * np.pi * n * dt / T)` 和 `T[-1, n] ==11` 修改为 `T[0, n] =10 + 12 * np.sin(2 * np.pi * n * dt / T)` 和 `T[-1, n] =11`。
2. 在每隔90天画一次图的条件判断中,应该使用 `n % int(T / (90*dt)) == 0` 而不是 `n % int(T / 4) == 0`,因为要画图的时间间隔是90天,而不是总时间的四分之一。
修改后的代码如下:
```
import numpy as np
import matplotlib.pyplot as plt
# 设置模拟参数
D = 0.12 # 热扩散率
L = 20 # 模拟深度
T = 365 * 10 # 模拟时间
h = 0.1 # 栅格大小
dt = 0.01 # 时间步长
N = int(T / dt) # 时间步数
M = int(L / h) + 1 # 深度格点数
K = int(T / (90*dt)) # 画图次数
# 初始化温度分布
T0 = np.ones(M) * 10
T0[0] = 10 + 12 # 表面温度
T0[-1] = 11 # 深度为20米处温度
# 初始化温度矩阵
T = np.zeros((M, N))
T[:, 0] = T0
# 进行数值求解
for n in range(1, N):
for i in range(1, M - 1):
T[i, n] = T[i, n-1] + D * dt / h**2 * (T[i+1, n-1] - 2*T[i, n-1] + T[i-1, n-1])
# 边界条件
if T.all()!=0:
T[0, n] = 10 + 12 * np.sin(2 * np.pi * n * dt / T)
T[-1, n] = 11
else:
break
# 每隔90天画一次图
if n % int(T / (90*dt)) == 0:
plt.plot(T[:, n], np.linspace(0, L, M), label=f'{n*dt/365:.0f} year')
plt.legend()
# 显示温度轮廓图
plt.xlabel('Temperature (°C)')
plt.ylabel('Depth (m)')
plt.title('Temperature Profile')
plt.gca().invert_yaxis()
plt.show()
```
这样就可以画出正确的温度轮廓图了。
阅读全文
相关推荐















