0%

一维热传导方程的 CN 格式

一维热传导方程 Crank-Nicolson 格式的 MATLAB 编程实现

一维热传导方程

其中 是正常数, 为已知函数。 为初始条件, 为边界条件。

Crank-Nicolson 格式

以空间步长 、时间步长 分别将 轴上区间 轴上区间 分成 等分,可得

一维热传导方程的六点对称格式Crank- Nicolson格式

以上格式可改写为

利用 和边值便可逐层求到 。六点对称格式是隐格式,由第 层计算第 层时,需解线性代数方程组(因系数矩阵严格对角占优,方程组可唯一求解)。

差分格式可以写为矩阵形式:

其中矩阵 、向量 的定义如下,注意向量 的首尾元素已包含了边界条件。

数值例子

其中 .

方程的真解:.

计算数值解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
% fdm_cn.m
% Crank-Nicolson scheme for heat equation
% u_t=u_{xx}+f(x,t), (x,t) in (0,1)x(0,1],
% u(x,0)=sin(x), x in [0,1],
% u(0,t)=sin(t), u(1,t)=sin(1+t), t in (0,1].
% f(x,t)=cos(x+t)+sin(x+t),
% exact solution: u(x,t)=sin(x+t)
clear all; close all;
a=1;
h=0.05; x=[0:h:1];
tau=0.001; t=[0:tau:1];
r=a*tau/h^2;
M=length(x)-1; N=length(t)-1;
% constructing the coefficient matrix
e=r*ones(M-1,1);
A=spdiags([-e 2+2*e -e],[-1 0 1],M-1,M-1);
B=spdiags([e 2-2*e e],[-1 0 1],M-1,M-1);
% setting initial and boundary conditions
u=zeros(M+1,N+1);
u(:,1)=sin(x);
u(1,:)=sin(t);
u(end,:)=sin(1+t);
for n=1:N
F=tau*cos(x(2:M)'+t(n))+tau*sin(x(2:M)'+t(n))...
+tau*cos(x(2:M)'+t(n+1))+tau*sin(x(2:M)'+t(n+1));
F(1)=F(1)+r*u(1,n)+r*u(1,n+1);
F(M-1)=F(M-1)+r*u(end,n)+r*u(end,n+1);
% solving the system
u(2:M,n+1)=A\B*u(2:M,n)+A\F;
end
% plot the figure
mesh(t(1:20:end),x,u(:,1:20:end))
set(gca,'fontsize',12)
xlabel('t','fontsize', 14)
ylabel('x','fontsize',14)
zlabel('u','fontsize',14)

% calculating maximum error
[T X]=meshgrid(t,x);
ue=sin(X+T);

Error=max(max(abs(ue-u)))

% print -dpng -r600 fdm_cn.png
% print -depsc2 fdm_cn.eps

输出结果

1
2
Error =
2.4988e-05

fdm_cn.png