Leapfrog Method with RK2 as a Start-up Scheme in MATLAB

Let's consider the following differential equation:

y'' + 10 y' + 500y = 0
Where, the initial conditions are,

y(0) = -0.025, and y'(0) = -1

We will solve this differential equation using a multi-step method, Leapfrog, where second order Runge-Kutta approach (RK2) is added as a start-up scheme in the algorithm. The following MATLAB program implements the Leapfrog method with initialization with RK2 method.

MATLAB Program:

close all;
clc;
h = 0.02;     % Step size
Tmax = 0.5;    % Maximum time
N = Tmax / h;  % Maximum number of steps
alpha=0.5;
t = linspace(0,0.5,N+1);  % Time range

% Analytical solution of the differential equation
y_real = -(((9.*sqrt(19))/760).*exp(-5.*t).*sin(5.*sqrt(19).*t)) - ((1/40).*exp(-5.*t).*cos(5.*sqrt(19).*t));
plot(t,y_real);
hold on

%Numerical solution
f=@(t,y) [y(2); -500*y(1)-10*y(2)]; % Governing system of equations

% Initial Conditions
Y = [-0.025; -1];
% Initialization with second order Runge-Kutta method
k1 = h.*f(t(1),Y(:,1));
    k2 = h.*f(t(1)+alpha.*h, Y(:,1)+alpha.*k1);
    Y(:,2) = Y(:,1) + (1-1/2/alpha).*k1 + k2/2/alpha;

% Leapfrog method steps
for i=2:N
    Y(:,i+1) = Y(:,i-1) + 2.*h.*f(t(i),Y(:,i));
end
plot(t,Y(1,:),'o:')
legend('Exact Solution','Leapfrog Solution','Location','NorthEast')
title('When h = 0.001')
xlabel('t')

ylabel('y')


Program Output:

The following plot shows the numerical and analytical solution of the differential equation with respect to time.

Numerical and Analytical Solution with Time

No comments:

Post a Comment