Leapfrog/Midpoint ODE Method - Incorrect
조회 수: 2 (최근 30일)
이전 댓글 표시
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;
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개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Error Functions에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!