%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import math
def f(k, r, t):
return k * math.e ** (r * t)
k = 4
r = 0.5
x = np.linspace(0, 20, 4000)
plt.plot(x, f(k, r, x))
[<matplotlib.lines.Line2D at 0x10cc6d190>]
p = 4
sim_length = 20
delta_t = 1
xs = []
ys = []
growth_rate_per_step = r * delta_t
num_iter = int(sim_length / delta_t) + 1
for i in range(num_iter):
xs.append(i * delta_t)
ys.append(p)
p += growth_rate_per_step * p
plt.plot(x, f(k, r, x))
plt.plot(xs, ys)
[<matplotlib.lines.Line2D at 0x10cb65a90>]
as we shrink the delta_t, we get closer and closer to the actual solution. local error (error per step) is proportional to the square of the step size
time = []
pop = []
simLength = 120
population = 4
M = 500.0
growthRate = 0.1
deltaT = 0.025
growthRatePerStep = growthRate * deltaT
numIterations = int(simLength / deltaT) + 1
for i in range(numIterations):
population += growthRatePerStep * population * (1 - population / M)
# population *= 1 + growthRatePerStep
time.append(i * deltaT)
pop.append(population)
plt.plot(time, pop)
[<matplotlib.lines.Line2D at 0x10d279fd0>]
time = []
temperature = []
simLength = 70
temp = 98.6
growthRate = 0.023079
envTemp = 72
deltaT = 0.0025
growthRatePerStep = growthRate * deltaT
numIterations = int(simLength / deltaT) + 1
for i in range(numIterations):
temp += -growthRatePerStep * (temp - envTemp)
# population *= 1 + growthRatePerStep
time.append(i * deltaT)
temperature.append(temp)
plt.plot(time, temperature)
plt.plot(time, [82] * len(time))
temperature[-1]
77.28713710191359
77.01188191620392