Page - 106 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 106 -
Text of the Page - 106 -
106 4 SolvingOrdinaryDifferentialEquations
from numpy import linspace, zeros, exp
import matplotlib.pyplot as plt
def ode_FE(f, U_0, dt, T):
N_t = int(round(float(T)/dt))
u = zeros(N_t+1)
t = linspace(0, N_t*dt, len(u))
u[0] = U_0
for n in range(N_t):
u[n+1] = u[n] + dt*f(u[n], t[n])
return u, t
def demo_population_growth():
"""Test case: uβ=r*u, u(0)=100."""
def f(u, t):
return 0.1*u
u, t = ode_FE(f=f, U_0=100, dt=0.5, T=20)
plt.plot(t, u, t, 100*exp(0.1*t))
plt.show()
if __name__ == β__main__β:
demo_population_growth()
Thisprogramfile, calledode_FE.py, is a reusablepieceof codewith ageneral
ode_FE function that can solve anydifferential equationu0 Df.u;t/ and ademo
function for the special caseu0 D 0:1u,u.0/ D 100. Observe that the call to the
demo function is placed in a test block. This implies that the call is not active if
ode_FE is importedasamodule inanotherprogram,butactive ifode_FE.py is run
asaprogram.
Thesolutionshouldbeidentical towhatthegrowth1.pyprogramproduceswith
the sameparameter settings (r D0:1,N0 D100). This featurecaneasilybe tested
byinsertingaprintstatement,butamuchbetter,automatedverificationissuggested
inExercise4.1.Youare stronglyencouraged to takeaβbreakβanddo that exercise
now.
Remarkontheuseofuasvariable
In theode_FEprogram, the variableu is used in different contexts. Inside the
ode_FE function,u is anarray,but in thef(u,t) function,asexemplified in the
demo_population_growth function, the argument u is a number. Typically,
we callf (inode_FE)with theu argument as one element of the arrayu in the
ode_FE function:u[n].
4.1.6 MakingthePopulationGrowthModelMoreRealistic
Exponential growthofapopulationaccording themodelN 0 D rN ,with exponen-
tial solutionN DN0ert, isunrealistic in the longrunbecause theresourcesneeded
to feed thepopulationarefinite. At somepoint therewill not beenough resources
and the growthwill decline. A commonmodel taking this effect into account as-
back to the
book Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python"
Programming for Computations β Python
A Gentle Introduction to Numerical Simulations with Python
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2016
- Language
- English
- License
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 248
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik