Numerical solution for the heat equation does not match the exact solution

71 次查看(过去 30 天)
I write a matlab code for the problem, and i want to compare the numerucal and the exact solution at t=0.5 but the graph of the soultions are very different.
The problem is in the following:
% Parameters
L = 5; % Length of the rod
T = 1; % Total time
Nx = 100; % Number of spatial points
Nt = 500; % Number of time steps
alpha = 0.01; % Thermal diffusivity
% Discretization
dx = 0.1; % Spatial step size
dt = 0.04; % Time step size
r = alpha * dt / dx^2; % Stability parameter for the scheme
% Initial condition
x = linspace(0, L, Nx);% generates Nx points. The spacing between the points is (L-0)/(Nx-1).
u = cos(x-0.5); % initial condition
% Preallocate solution matrix
U = zeros(Nx, Nt+1); % returns an Nx-by-Nt matrix of zeros
U(:,1) = u; %extracts all the elements from the first column of matrix
% Time-stepping loop
for n = 1:Nt
% Update the solution using explicit scheme for the Heat Equation
for i = 2:Nx-1
U(i,n+1) = U(i,n) + r * (U(i+1,n) - 2*U(i,n) + U(i-1,n));
end
end
Numerical_sol = U
% Plot results
t = linspace(0, T, Nt+1);
[X, T] = meshgrid(x, t);
% Exact solution
Exact= @(x, t) exp(-t) .* cos(pi * x - 0.5 * pi);
figure;
mesh(X, T, U');
xlabel('x');
ylabel('t');
zlabel('u(x,t)');
title('Heat Equation Solution');
figure
plot(x, U(:,1), 'o');
  2 个评论
John D'Errico
John D'Errico 2024-9-5,11:47
You accepted the answer to this question. Then you asked it just again, 42 minutes ago. I closed the duplicate question, since it asks nothing you should not have learned here.
Torsten
Torsten 2024-9-5,12:00
I didn't know that you are the Website Master taking the right to delete questions and answers that are actually in flow.

请先登录,再进行评论。

采纳的回答

Torsten
Torsten 2024-9-4,12:58
移动:Torsten 2024-9-4,12:59
I cannot believe that the value for alpha has no influence on the solution.
So I guess that the exact solution maybe holds for alpha = 1.
  10 个评论
Torsten
Torsten 2024-9-4,17:31
编辑:Torsten 2024-9-4,17:33
The exact solution for the differential equation
du/dt = alpha * d^2u/dx^2
with initial condition
u(0,x) = cos(pi*(x-0.5))
and boundary conditions
u(t,0) = u(t,1) = 0
is given by
uexact(t,x) = exp(-alpha*pi^2*t) * cos(pi*(x-0.5))
That's the function you have to compare the numerical solution with.
syms x t alpha pi
u = exp(-alpha*pi^2*t) * cos(pi*(x-0.5));
diff(u,t)
ans = 
alpha*diff(u,x,2)
ans = 

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Calculus 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by