Leapfrog/Midpoint ODE Method - Incorrect

2 ビュー (過去 30 日間)
Patddy
Patddy 2015 年 8 月 20 日
コメント済み: Patddy 2015 年 8 月 24 日
I simply don't understand why Leapfrog isn't working correctly, Euler does. The algorithm for Leapfrog should be:
y[n+1] = y[n-1] + 2*h*f(x[n],y[n])
x[n+1] = x[n] + h;
Following page 33 of: Here
Please help!
Leapfrog.m
function [ matrix ] = LeapfrogMethod( fun, initX, initY,...
steplength, maximum, opt_print )
%LEAPFROGMETHOD Solves the differential equation supplied
% Define variables
f = fun;
x0 = initX;
y0 = initY;
h = steplength;
n = maximum;
% Set up matrix
range = n/h;
matrix = zeros(range,2);
% Calculate first value
x1 = x0 + h;
euler = EulerMethod(f,x0,y0,h,h,0);
y1 = euler(1,2);
matrix(1,1) = x1;
matrix(1,2) = y1;
if (~exist('opt_print', 'var'))
fprintf('x = %3g, y = %3g\n',matrix(1,1),matrix(1,2))
end
% Method
for J = 2:range
matrix(J,2) = y0 + 2*h*f(x1,y1);
matrix(J,1) = x1 + h;
if (~exist('opt_print', 'var'))
fprintf('x = %3g, y = %3g\n',matrix(J,1),matrix(J,2))
end
x1 = matrix(J,1);
y0 = y1;
y1 = matrix(J,2);
end
%
end
EulerMethod.m
function [ matrix ] = EulerMethod( fun, initX, initY,...
steplength, maximum, opt_print )
%EULERMETHOD Solves the differential equation supplied
% Define variables
f = fun;
x0 = initX;
y0 = initY;
h = steplength;
n = maximum;
% Set up matrix
range = n/h;
matrix = zeros(range,2);
% Method
for J = 1:range
matrix(J,2) = y0 + h*f(x0,y0);
matrix(J,1) = x0 + h;
if (~exist('opt_print', 'var'))
fprintf('x = %3g, y = %3g\n',matrix(J,1),matrix(J,2))
end
x0 = matrix(J,1);
y0 = matrix(J,2);
end
%
end
  1 件のコメント
Patddy
Patddy 2015 年 8 月 24 日
Apologies, it was unstable and I was later asked why it was unstable. Nothing wrong with the code.

サインインしてコメントする。

回答 (1 件)

Varun Bhaskar
Varun Bhaskar 2015 年 8 月 24 日
Hi,
Can you elaborate on the question?
Thanks
  1 件のコメント
Patddy
Patddy 2015 年 8 月 24 日
Apologies, it was unstable and I was later asked why it was unstable. Nothing wrong with the code.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeError Functions についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by