Python 热传导方程的有限差分解法

Python 热传导方程的有限差分解法,python,numpy,numerical-methods,differential-equations,Python,Numpy,Numerical Methods,Differential Equations,在练习有限差分实现时,我无法理解为什么我的解决方案看起来如此奇怪。代码取自: 注:我用这个讲课的例子来解释热方程,而不是反应扩散方程 我还没有学过相关的数学,所以这可能是原因 我的代码: import numpy as np import matplotlib.pyplot as plt from matplotlib import cm import math as mth from mpl_toolkits.mplot3d import Axes3D import pylab as plb

在练习有限差分实现时,我无法理解为什么我的解决方案看起来如此奇怪。代码取自:

注:我用这个讲课的例子来解释热方程,而不是反应扩散方程

我还没有学过相关的数学,所以这可能是原因

我的代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import math as mth
from mpl_toolkits.mplot3d import Axes3D
import pylab as plb
import scipy as sp
import scipy.sparse as sparse
import scipy.sparse.linalg


# First start with diffusion equation with initial condition  u(x, 0) = 4x - 4x^2 and u(0, t) = u(L, t) = 0
# First discretise the domain [0, L] X [0, T]
# Then discretise the derivatives
# Generate algorithm:
# 1. Compute initial condition for all i
# 2. For all n:
#    2i. Compute u_i^{n + 1} for internal space points
#   2ii. Set boundary values for i = 0 and i = N_x



M = 40 # number of grid points for space interval
N = 70 # ''     '' ''   ''     ''  time ''

x0 = 0
xL = 1 # unit grid differences

dx = (xL - x0) / (M - 1) # space step

t0 = 0
tF = 0.2

dt = (tF - t0) / (N - 1)

D = 0.3 # thermal diffusivity 

a = D * dt / dx**2

# Create grid
tspan = np.linspace(t0, tF, N)
xspan = np.linspace(x0, xL, M)


# Initial matrix solution
U = np.zeros((M, N))

# Initial condition
U[:, 0] = 4*xspan - 4*xspan**2
# Boundary conditions
U[0, :] = 0
U[-1, 0] = 0

# Discretised derivative formula
for k in range(0, N-1):
    for i in range(1, M-1):
        U[i, k+1] = a * U[i-1, k] + (1 - 2 * a) * U[i, k] + a * U[i + 1, k]


X, T = np.meshgrid(tspan, xspan)

fig = plt.figure()
ax = fig.gca(projection='3d')

surf = ax.plot_surface(X, T, U, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)

ax.set_xticks([0, 0.05, 0.1, 0.15, 0.2])

ax.set_xlabel('Space')
ax.set_ylabel('Time')
ax.set_zlabel('U')
plt.tight_layout()
plt.show()

编辑:将therm diff值更改为正确值。

主要问题是时间步长。如果你看一下微分方程,数值在
a>0.5时变得不稳定。这对您来说意味着大致
N>190
。如果我将你的
N
增加到这样的值,我会得到一张很好的图片

然而,我发现时间轴和空间轴在某处交换(如果你试图解释图形,那么,即边界条件和预期的剖面随时间衰减)。我现在不明白为什么

编辑:实际上,在执行
meshgrid
时,您可以交换
T
X
。这应该起作用:

    N = 200

...
...

    T, X = np.meshgrid(tspan, xspan)

...

    surf = ax.plot_surface(T, X, U, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)

...

    ax.set_xlabel('Time')
    ax.set_ylabel('Space')

请将其降低并提高到预期值。显示中间结果与预期结果的偏差。如果你还没有学会基本的数学,那么在发帖之前你还有更多的工作要做。谢谢,这会让你明白很多。稳定性是我最困惑的部分。我要再看一本数值分析教科书!