%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
def derivs(s,t):
f = s[1]
c = s[0]
dfdt = -.1*f + 0.15*f*c
dcdt = +0.1*c - 0.15*f*c
return np.array([dcdt,dfdt])
def EulerStep(s, t, derivs, dt):
"""
EulerStep is a generic implimentation of the Euler Algorithm.
Notice that it knows *nothing* about the state, nor the physics
of the problem (which is handled by the 'derivs' function
that is passed in by the programmer).
"""
return s + derivs(s,t)*dt
def HeunStep(s, t, derivs, dt):
"""
HeunStep is a generic implimentation of the Heun Method.
Notice that it knows *nothing* about the state, nor the physics
of the problem (which is handled by the 'derivs' function
that is passed in by the programmer).
"""
f1=derivs(s,t)
f2=derivs(s+f1*dt,t+dt)
return s + 0.5*(f1+f2)*dt
def analyticalChicken(t , animal):
test = np.array(t)
return animal * np.exp(test * .1)
def analyticalFox(t , animal):
test = np.array(t)
return animal * np.exp(test * -.1)
Chicken = 20
Fox = 0
dt = 0.03 # pick a reasonable time step
t = 0.0 # start at t=0.0
tf = 10.0 # stop in 10
tlist = []
while(t < tf):
t= t + dt
tlist.append(t)
ChickenSlope = analyticalChicken(tlist,Chicken)
FoxSlope = analyticalFox(tlist,Fox)
plt.xlabel("Time")
plt.ylabel("Number of Animals")
plt.plot(ChickenSlope, label="chicken")
plt.plot(FoxSlope, label="fox")
plt.legend()
Chicken = 0
Fox = 20
dt = 0.03 # pick a reasonable time step
t = 0.0 # start at t=0.0
tf = 10.0 # stop in 10
s = np.array([Chicken, Fox]) ## chicken, foxes
tlist = []
slist = []
while(t < tf):
s = HeunStep(s,t,derivs,dt)
t = t + dt
tlist.append(t)
slist.append(s)
ChickenSlope = analyticalChicken(tlist, Chicken)
FoxSlope = analyticalFox(tlist, Fox)
plt.xlabel("Time")
plt.ylabel("Number of Chickens and Foxes")
plt.plot(tlist, slist, 'r-')
plt.plot(tlist,ChickenSlope, 'b:', linewidth=4)
plt.plot(tlist, FoxSlope, 'g:', linewidth=4)
plt.legend(["HuenChicken", "HuenFox", "AnalyticalChicken", "AnalyticalFox",])