Skip to article frontmatterSkip to article content

Instability of forward Euler scheme

from pylab import *

Adaptive stepping

We will use a variable time step

yn=yn1+hn1f(tn1,yn1)y_n = y_{n-1} + h_{n-1} f(t_{n-1}, y_{n-1})

where

hn1=1fy(tn1,yn1)=110tn1yn1h_{n-1} = \frac{1}{|f_y(t_{n-1},y_{n-1})|} = \frac{1}{10 t_{n-1} |y_{n-1}|}
def aeuler(f,t0,T,y0):
    t, y = [], []
    y.append(y0)
    t.append(t0)
    time = t0; n = 1
    while time < T:
        h    = 1.0/abs(10*t[n-1]*y[n-1])
        y.append(y[n-1] + h*f(t[n-1],y[n-1]))
        time = time + h
        t.append(time)
        n = n + 1
    return array(t), array(y)
t,y = aeuler(f,t0,T,y0)
print('Number of iterations=',len(t))

plot(t,y,te,ye,'--')
legend(('Numerical','Exact'))
xlabel('t')
ylabel('y');

figure()
plot(range(len(t)-1),t[1:]-t[0:-1])
ylabel('Step size, h')
xlabel('Iteration');
Number of iterations= 241
<Figure size 640x480 with 1 Axes><Figure size 640x480 with 1 Axes>