Error convergence plot: Finding the exact and numerical solution of an ODE using different timesteps and plotting the error between these solutions Vs the different discretization or timesteps.

8 visualizaciones (últimos 30 días)
I'm trying to iterate through different timesteps and solving both the exact and numerical solution to a an initial value ordinary differential equation. I'm using the L2 error norm method to find the error between my analytical and numerical solution and then plotting the error vs the different timesteps. However, for some reason my code does not give me the accurate exact solution results. Also, my error seems to increase with discretization/timestep which is wrong. Can you please help me? Here is my code:
function [error_y1,Exact,Numerical] = Conv
clear all;
clear; clc;
tic;
%% Exact (analytical) solution function
syms y(x);
Dy =diff(y);
ODE =diff(y,x,2) == -4*diff(y,x)-(8*(y));
ODE=diff(y,x,2) == -4*diff(y,x,1)- (8*(y));
cond1 =y(0)==1; cond2=Dy(0)==0;
conds=[cond1 cond2];
ySol(x)=dsolve(ODE,conds);
ySol=simplify(ySol);
Exact=ySol;
%% Setting up and iterating through both exact and numerical solution
%Setting up time-step and number of iteration per timestep
y0 = 1; % initial condition
m_list = 10:10:100; % number of iterations to get to t=1
h_list = 1./m_list; % step size
n = length(m_list);
error_y1 = zeros(1,n); % to hold the final point
Exact=zeros(1,n);
Numerical=zeros(1,n);
sum=0;
for i=1:n % loop over different step sizes
m = m_list(i); % get the number of iterations
h = h_list(i); % get step size
y1 = y0; % start with y(0)
for t=1:m % iterating through euler and exact solution
y1_list=@(h) (1+h)*y1; % Euler solution iteration begins here
Exactf=@(h) double(ySol(h)); % Exact solution iteration begins here
Exact(i)=double(Exactf(h));
Numerical(i)=double(y1_list(h));
f =@(h) ((y1_list(h)-Exactf(h))^2);
% set up to iterate throughnumerical integration of the function f
for u=1:1:m-1
e(u)=0+(u*h);
k(u)=f(e(u));
sum=sum+f(u);
end
% numerical integration using trapezoidal method begins from here.
err=h/2*(f(0)+f(1)+2*sum);
err2=sqrt(err/m);
error_y1(i)=double(err2);
end
end
%% Plotting exact solution & numerical solution Vs discretization on the same graph
plot (h_list,Exact, '-or');
hold on
plot (h_list,Numerical, '-xb');
%% Plotting log error Vs log discretization
subplot(121);plot(h_list, error_y1, '-o')
title('error -- h');xlabel('h');ylabel('error')
subplot(122);loglog(h_list, error_y1, '-o')
title('log(error) -- log(h)');xlabel('log(h)');ylabel('log(error)')
toc;
end

Respuestas (0)

Categorías

Más información sobre Ordinary Differential Equations en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by