numpy 数组和方法非常有用。它们通常经过优化,比在 python 中循环要快得多。始终寻找一种方法来为您的应用程序使用现有的 numpy 方法。
np.roll()将允许您转移,然后您只需添加。
我convolve()从关于如何更快地 np.roll() 的评论中学会了使用?. 我没有检查这是否更快,但这可能取决于维度的数量。请参阅此答案以了解拉普拉斯方程的 2D 松弛(静电,另一个问题)
对于这种放松,你需要一个边界框,所以布尔值do_me在False边界上。
我知道对于拉普拉斯方程的雅可比松弛解,有两种加速方法。我不知道它们是否可以扩展到求解热扩散方程,但我确信可以做一些事情:

import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import convolve
T0 = np.zeros(50, dtype=float)
T0[17:25] = 1.
T1 = T0.copy() # method 1 np.roll()
T2 = T0.copy() # method 2 convolve()
do_me = np.ones_like(T0, dtype=bool)
do_me[[0, -1]] = False # keep the boundaries of your bounding box fixed
a = 0.01
hold_1 = [T0.copy()]
for i in range(10001):
Ttemp = T1 + a*(np.roll(T1, +1) + np.roll(T1, -1) - 2*T1)
T1[do_me] = Ttemp[do_me]
if not i%1000:
hold_1.append(T1.copy())
hold_2 = [T0.copy()]
kernel = np.array([a, (1 - 2.*a), a])
for i in range(10001):
Ttemp = convolve(T2, kernel)
T2[do_me] = Ttemp[do_me]
if not i%1000:
hold_2.append(T2.copy())
if True:
plt.figure()
plt.subplot(1, 2, 1)
for thing in hold_1:
plt.plot(thing)
plt.subplot(1, 2, 2)
for thing in hold_2:
plt.plot(thing)
plt.show()