#----------------------------------------------------------------------
#
# eulermethod.py
#
# calculate the curve which is the solution to an ordinary differential
# equation with an initial value using Euler's Method
#
# Paul Soper
#
# April 24, 2016
#
#-----------------------------------------------------------------------
In [2]:
import math
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
In [3]:
# we will use the differential equation y'(t) = y(t). The analytic solution is y = e^t.
def y1(t,y):
return y
def asol(t):
return math.exp(t)
yasol = np.vectorize(asol)
In [4]:
h = 0.1
t0 = 0.0
y0 = 1.0
t = np.arange(0.0, 5.0, h)
y = np.zeros(t.size)
y[0] = y0
In [5]:
for i in range(1, t.size):
y[i] = y[i-1] + y1(t[i-1],y[i-1])*h
In [6]:
plt.plot(t,y,'r-',t,yasol(t),'b-')
