I would appreciate if someone can help with the following issue. I have the following ODE:
dr/dt = 4*exp(0.8*t) - 0.5*r ,r(0)=2, t[0,1] (1)
I have solved (1) in two different ways.
By means of the Runge-Kutta method (4th order) and by means of ode45
in Matlab. I have compared the both results with the analytic solution, which is given by:
r(t) = 4/1.3 (exp(0.8*t) - exp(-0.5*t)) + 2*exp(-0.5*t)
When I plot the absolute error of each method with respect to the exact solution, I get the following:
For RK-method, my code is:
h=1/50;
x = 0:h:1;
y = zeros(1,length(x));
y(1) = 2;
F_xy = @(t,r) 4.*exp(0.8*t) - 0.5*r;
for i=1:(length(x)-1)
k_1 = F_xy(x(i),y(i));
k_2 = F_xy(x(i)+0.5*h,y(i)+0.5*h*k_1);
k_3 = F_xy((x(i)+0.5*h),(y(i)+0.5*h*k_2));
k_4 = F_xy((x(i)+h),(y(i)+k_3*h));
y(i+1) = y(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h; % main equation
end
And for ode45
:
tspan = 0:1/50:1;
x0 = 2;
f = @(t,r) 4.*exp(0.8*t) - 0.5*r;
[tid, y_ode45] = ode45(f,tspan,x0);
My question is, why do I have oscillations when I use ode45
? (I am referring to the absolute error). Both solutions are accurate (1e-9
), but what happens with ode45
in this case?
When I compute the absolute error for the RK-method, why does it looks nicer?