Runge - kutta 4th order method for two different steps

48 ビュー (過去 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