Runge-Kutta method: Difference between revisions

Line 1,593:
 
=={{header|Octave}}==
<lang octave>
{{incomplete}}
#Applying the Runge-Kutta method (This code must be implement on a different file than the main one).
Implementing Runge-Kutta in octave is a bit of a hassle. For now we'll showcase how to solve an ordinary differential equation using the lsode function.
Edited by Alicatoso: I applied the Runge-Kutta to solve, but I'm having problem in printing the values(program gives an error message when I try to print inside a loop). Because of that, I will left the unedited program, until someone solve the printing problem.
 
<lang octave>function ydot = f(y, t)
ydot = t * sqrt( y );
endfunction
t = [0:10]';
y = lsode("f", 1, t);
[ t, y, y - 1/16 * (t.**2 + 4).**2 ]
 
#Applying the Runge-Kutta method
function temp = rk4(func,x,pvi,h)
K1 = h*func(x,pvi);
Line 1,614 ⟶ 1,603:
temp = pvi + (K1 + 2*K2 + 2*K3 + K4)/6;
endfunction
 
#Main Program.
 
f = @(t) (1/16)*((t.^2 + 4).^2);
Line 1,621 ⟶ 1,612:
h = 0.1;
Yn = pvi;
 
 
for x = 0:h:10-h
pvi = rk4(df,x,pvi,h);
Yn = [Yn pvi];
endfor
 
end</lang>
fprintf('Time \t Exact Value \t ODE4 Value \t Num. Error\n');
{{out}}
<pre>ans =
 
for i=0:10
0.00000 1.00000 0.00000
fprintf('%d \t %.5f \t %.5f \t %.4g \n',i,f(i),Yn(1+i*10),f(i)-Yn(1+i*10));
1.00000 1.56250 0.00000
endfor
2.00000 4.00000 0.00000
end</lang>
3.00000 10.56250 0.00000
{{out}}
4.00000 25.00000 0.00000
<pre>ans =
5.00000 52.56250 0.00000
Time 6.00000Exact Value 100.00000 ODE4 Value 0 Num.00000 Error
0 7 1.00000 175.56250 0 1.00000 0
1 8 1.0000056250 289 1.0000156250 01.00001457e-007
2 9 4.00000 451 4.5625100000 0 9.00001195e-007
3 10.0000056250 676 10.0000156250 02.00001</pre>91e-006
4 0 25.00000 1 24.0000099999 0 6.00000235e-006
5 52.56250 52.56249 1.082e-005
6 1 100.00000 1 99.5625099998 0 1.00000659e-005
7 175.56250 175.56248 2.352e-005
8 2 289.00000 4 288.0000099997 0 3.00000157e-005
9 451.56250 451.56246 4.072e-005
10 676.00000 675.99995 5.098e-005</pre>
 
=={{header|PARI/GP}}==
Anonymous user