Runge - kutta 4th order method for two different steps

조회 수: 5 (최근 30일)
Left Terry
Left Terry 2024년 12월 31일
댓글: Torsten 2024년 12월 31일
Why is h = 0.5 worst than h = 1 in my code ? I can't find where i am wrong.
clc, clear all, close all, format long
f = @(x,y) y;
h = [1 0.5];
y0 = 1;
syms Y(X)
Df = diff(Y) == Y;
Y = dsolve(Df, Y(0) == 1);
fplot(X,Y), hold on
for i = 1:length(h)
x = [0:h(i):4];
for j = 1:length(x)-1
y(1) = y0;
K1 = f(x(j),y(j));
K2 = f(x(j) + 0.5*h(i), y(j) + 0.5*h(i)*K1);
K3 = f(x(j) + 0.5*h(i), y(j) + 0.5*h(i)*K2);
K4 = f(x(j) + h(i), y(j) + h(i)*K3);
y(j+1) = y(j) + (K1 + K4 + 2*(K2 + K3))/6;
end
xlim([0 5]), ylim([0 55])
plot(x,y)
end
legend({'y(x) = e^x','Runge - Kutta 4th order with h = 1','Runge - Kutta 4th order with h = 0.5'},'Location','Best')

채택된 답변

Torsten
Torsten 2024년 12월 31일
y(j+1) = y(j) + h(i)*(K1 + K4 + 2*(K2 + K3))/6;
instead of
y(j+1) = y(j) + (K1 + K4 + 2*(K2 + K3))/6;
  댓글 수: 2
Left Terry
Left Terry 2024년 12월 31일
Yes, you are right and I...need to visit the eye doctor. Thank you.
Torsten
Torsten 2024년 12월 31일
And you should take the assignment
y(1) = y0;
out of the j-loop. Assigning once at the start is sufficient.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

제품


릴리스

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by