Runge - kutta 4th order method for two different steps

5 Ansichten (letzte 30 Tage)
Left Terry
Left Terry am 31 Dez. 2024
Kommentiert: Torsten am 31 Dez. 2024
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')

Akzeptierte Antwort

Torsten
Torsten am 31 Dez. 2024
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 Kommentare
Left Terry
Left Terry am 31 Dez. 2024
Yes, you are right and I...need to visit the eye doctor. Thank you.
Torsten
Torsten am 31 Dez. 2024
And you should take the assignment
y(1) = y0;
out of the j-loop. Assigning once at the start is sufficient.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte


Version

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by