Runge-Kutta fourth order with negative stepsize
Solution 1:
If you have a procedure
y_next = rk4step(f,t,y,h)
that works correctly for positive h
, then this same procedure also works correctly for negative h
. Remember that the time step remains
t_next = t+h
The only problem that may arise is the control of the loop. If the sampling times are given as array, then the loop
for k in range(1,len(t)):
y[k] = rk4step(f,t[k-1],y[k-1], t[k]-t[k-1])
will work independent of the direction of the time sample points.
If the loop control is based on the end time, then while t < tf
works for positive h
, for negative h
one has to switch the sign or include h
as in while 0<(tf-t)*h
.