import numpy as np import matplotlib.pyplot as plt def ydot(t,y): # right-hand side of differential equation #z = t+y # oppgave (a) z = t-y # oppgave (b) #z = 4*t-2*y # oppgave (c) return z def eulerstep(t,y,h): # one step of Euler's Method # Input: current time t, current value y, stepsize h # Output: approximate solution value at time t+h y=y+h*ydot(t,y) return y def oppgave_6_1_5(y_exact): k = range(5) H = [] E = [] for k in range(10): h = 0.1*2**(-k) n = round(1/h) t = 0 y = 0 for i in range(n): y = eulerstep(t, y, h) t = t + h H.append(h) E.append(abs(y - y_exact(1))) # plot the error vs h plt.figure(0) plt.clf() fs = 12 # font size plt.loglog(H,E,'x-',lw=3, markersize=10) plt.xlabel('h', fontsize=fs) plt.ylabel('Error',fontsize=fs) plt.grid(True) plt.show() if __name__ == "__main__": # Exact solution: # (a) #y_exact = lambda t: -t-1+np.exp(t) # (b) y_exact = lambda t: t-1+np.exp(-t) oppgave_6_1_5(y_exact)