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)
ode45 is coupled rk4-rk5. Personally I think the ODE45 error is nicer. Notice that it stays bounded. The ode4 gets corrected when error magnitude gets too big, and the minimum error per cycle is about 1e-10. The rk4 is "running away" and nothing is stopping it.
Your RK4 function is taking fixed steps that are much smaller than those that ode45
is taking. What you're really seeing is the error due to polynomial interpolation that is used to produce the points in between the true steps that ode45
takes. This is often referred to as "dense output" (see Hairer & Ostermann 1990).
When you specify a TSPAN
vector with more than two elements, Matlab's ODE suite solvers produce fixed step size output. This does not mean that they that they actually use a fixed step size or that they use the step sizes specified in your TSPAN
however. You can see the actual step sizes used and still get your desired fixed step size output by having ode45
output a structure and using deval:
sol = ode45(f,tspan,x0);
diff(sol.x) % Actual step sizes used
y_ode45 = deval(sol,tspan);
You'll see that after an initial step of 0.02
, because your ODE is simple it converges to 0.1
for the subsequent steps. The default tolerances combined with the default maximum step size limit (one tenth the integration interval) determine this. Let's plot the error at the true steps:
exactsol = @(t)(4/1.3)*(exp(0.8*t)-exp(-0.5*t))+2*exp(-0.5*t);
abs_err_ode45 = abs(exactsol(tspan)-y_ode45);
abs_err_ode45_true = abs(exactsol(sol.x)-sol.y);
abs_err_rk4 = abs(exactsol(tspan)-y);
figure;
plot(tspan,abs_err_ode45,'b',sol.x,abs_err_ode45_true,'k.',tspan,abs_err_rk4,'r--')
legend('ODE45','ODE45 (True Steps)','RK4',2)
As you can see, the error at the true steps grows more slowly than the error for RK4 (ode45
is effectively a higher order method than RK4 so you'd expect this). The error grows in between the integration points due to the interpolation. If you want to limit this, then you should adjust the tolerances or other options via odeset.
If you wanted to force ode45
to use a step of 1/50
you can do this (works because your ODE is simple):
opts = odeset('MaxStep',1/50,'InitialStep',1/50);
sol = ode45(f,tspan,x0,opts);
diff(sol.x)
y_ode45 = deval(sol,tspan);
For another experiment, try enlarging the integration interval to integrate out to t = 10
maybe. You'll see lots of interesting behavior in the error (plotting relative error is useful here). Can you explain this? Can you use ode45
and odeset
to produce results that behave well? Integrating exponential functions over large intervals with adaptive step methods is challenging and ode45
is not necessarily the best tool for the job. There are alternatives however, but they may require some programming.