You are on page 1of 4

Runge-Kutta Method

4th Order Runge-Kutta Method (Average slopes of 4 points to approximate the result)
 
𝒇˙  𝟒 : 𝒔𝒍𝒐𝒑𝒆 𝒊𝒏 𝒆𝒏𝒅𝒑𝒐𝒊𝒏𝒕
current value
 
= next value
 

=
=
=
  𝒇˙  𝟑 : 𝒔𝒍𝒐𝒑𝒆 𝒊𝒏 𝒎𝒊𝒅 − 𝒑𝒐𝒊𝒏𝒕
= =

 
=
𝒇˙  𝟐 : 𝒔𝒍𝒐𝒑𝒆 𝒊𝒏 𝒎𝒊𝒅 − 𝒑𝒐𝒊𝒏𝒕
𝑦  0
𝒇˙  𝟏 : 𝒔𝒍𝒐𝒑𝒆 𝒊𝒏 𝒊𝒏𝒊𝒕𝒊𝒂𝒍 𝒑𝒐𝒊𝒏𝒕

h 𝑡  0+ h
𝑡 0 𝑡  0+
2
clear
close all
%% the function is mv'=-bv+f intitial condition v(0)=0.5  
%% the exact solution is v=f/b+(-f/b+0.5)*exp((-b/m)*t))
%%
m=1;
b=2;
f=3;
tstart=0;
tend=10;
h = 0.001; %%change to small step size (0.1 or 0.01) then the result of numerical
method will be better Time step
t = tstart:h:tend;
v_num(1) = 0.5;
t(1) = 0;
v_exact(1) =0.5;
%fprintf('Step 0: t = %12.8f, w = %12.8f\n', t, w);
for i=2:size(t,2)
Slop of Point1
k1 = h*fnum(t(i-1),v_num(i-1));
Slop of Point2
k2 = h*fnum(t(i-1)+h/2, v_num(i-1)+k1/2); 4th-Order Runge-Kutta Method
Slop of Point3
k3 = h*fnum(t(i-1)+h/2, v_num(i-1)+k2/2); V_num(1)=v(0)=0.5
k4 = h*fnum(t(i-1)+h, v_num(i-1)+k3); Slop of Point4
Iteration from 2 to final step
v_num(i) = v_num(i-1) + (k1+2*k2+2*k3+k4)/6;
end
yt=tstart:0.01:tend;
y(1) =0.5;
for i=2:size(yt,2) Get Exact Result
v_exact(i) = fexact(yt(i)); Time interval:0.01
end
figure
plot(t,v_num)
hold on
plot(yt,v_exact) Plot Result
legend('RK Method','exact result')
xlabel('time(s)')
ylabel('velocity(m/s)')
%%%%%%%%%%%%%%%%%%
function dv = fnum(t,v)
m=1;
b=2; Use to calculate the slope in Runge-Kutta Method
f=3;
dv = -b*v+f;
end
function v_exact = fexact(t)
m=1;
b=2; Use to calculate the exact solution
f=3;
v_exact=(f/b)+(-f/b+0.5)*exp((-b/m)*t);
end

You might also like