Reputation: 1661
I am solving the heat equation numerically using a forward time - centre space finite difference method.
My solution ceases to decay once I take a spacial step size small enough. Why is that?
I can't seem to figure it out, and I would really appreciate some help.
Here is my code:
TI=0; %Intial time
TF=1; %Final Time
sigma=2;
dx=0.01;
dt=(dx^2)/(5*sigma); %Ensure the criteria on r is met by chooding delta t in this way
r=sigma*dt/(dx^2);
x=-1:dx:1;
phi=sin(pi*x); %Initial cpndition
old=phi; %To be used in the algorithm
new=zeros(1,numel(x));
timesteps=(TF-TI)/dt; %Classically called n
timesteps=int8(timesteps); %Ensure this number is an integer so it doesnt make matlab mad
spacesteps=numel(x);
M=zeros(timesteps,spacesteps);
M(1,:)=phi; %Going to put all my computed time steps into a matrix.
for i=2:timesteps
%Now take dx space steps
for j=2:spacesteps-1
new(1)=0;
new(end)=0;
new(j)=old(j) + r*(old(j+1)-2*old(j)+old(j-1));
end
M(i,:)=new;
old=new;
new=zeros(1,numel(x));
end
DIM_M=size(M);
[X,T]=meshgrid(linspace(-1,1,DIM_M(2)),linspace(0,TF,DIM_M(1)));
figure(1)
surf(X,T,M);
xlabel('x')
ylabel('t')
title('Numerical Solution')
shading interp
AS=exp(-sigma*pi^2*T).*sin(pi*X);
figure(2)
surf(X,T,AS)
xlabel('x')
ylabel('t')
title('Actual Solution')
shading interp
Error=AS-M;
figure(3);
surf(X,T,Error)
shading interp
Upvotes: 0
Views: 53
Reputation: 283733
Selecting a few lines that are causing misbehavior.
TI=0;
TF=1;
sigma=2;
dx=0.01;
dt=(dx^2)/(5*sigma); // .01^2 == .0001, 5*sigma == 10, dt := .00001
timesteps=(TF-TI)/dt; // TF-TI == 1, 1/.00001 == 10000, timesteps := 10000
timesteps=int8(timesteps);
An out-of-range condition occurs in that final line. MATLAB clips overflows in type casts to the nearest representable value, so you actually get timesteps = 127
and your invariant that TF == TI + dt * timesteps;
is violated. The simulation will stop far short of TF
.
Upvotes: 1