#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun  3 13:21:21 2019

@author: kerkmann
"""

import numpy as np
import matplotlib.pyplot as plt

# explicit Euler method (from exercise 27)
def Euler_explicit(x,t,f,k):
    return x + k*f(x,t)


### MAIN PROGRAM ###

l = 10**2
f = lambda u,t: -l*u
t_0 = 0
T = 1
U = [1]

kstart = 0.9
err = 1

it = -1

# iterate until the error is small
while (err > 1e-3):
    it = it + 1
    k = kstart*(.9)**it
    t = t_0
    n = 0
    
    # initial data
    U = [1]
    while t<T:
        # match final time
        if (t+k) > T:
            k = T - t
    
        # approximation with Euler
        U.append(Euler_explicit(U[n],t,f,k))
        n = n+1
        t = t+k
    
    err = abs(U[-1] - np.exp(-l*T))
    print(kstart*(.9)**it, err)
    
# plot
U = np.array(U)
plt.plot(np.linspace(t_0,T,n+1),U)