276
8 Solving Ordinary Differential Equations
values, modify the program osc_FE.py to dump the u array to file, run osc_FE.py,
and let the test function read the reference results from that file.
Filename: osc_ode_FE.py.
Exercise 8.11: Compute the Energy in Oscillations
a) Make a function osc_energy(u, v, omega) for returning the potential and
kinetic energy of an oscillating system described by (8.43)–(8.44). The potential
energy is taken as
1
2 ω 2 u 2 while the kinetic energy is
1
2 v 2 . (Note that these
expressions are not exactly the physical potential and kinetic energy, since these
would be
1
2 mv 2 and
1
2 ku 2 for a model mx + kx = 0.)
Place the osc_energy in a separate file osc_energy.py such that the
function can be called from other functions.
b) Add a call to osc_energy in the programs osc_FE.py and osc_EC.py and plot
the sum of the kinetic and potential energy. How does the total energy develop
for the Forward Euler and the Euler-Cromer schemes?
Filenames: osc_energy.py, osc_FE_energy.py, osc_EC_energy.py.
Exercise 8.12: Use a Backward Euler Scheme for Population Growth
We consider the ODE problem N (t) = rN(t), N(0) = N 0 . At some time,
t n = nΔt, we can approximate the derivative N (t n ) by a backward difference,
see Fig. 8.22:
N
(t n ) ≈
N(t n ) − N(t n − Δt)
Δt
=
N n − N n−1
Δt
,
which leads to
N n − N n−1
Δt
= rN
n ,
called the Backward Euler scheme.
a) Find an expression for the N n in terms of N n−1 and formulate an algorithm for
computing N n , n = 1, 2, . . . , N t .
b) Implement the algorithm in a) in a function growth_BE(N_0, dt, T) for
solving N = rN, N(0) = N 0 , t ∈ (0, T ], with time step Δt (dt).
c) Implement the Forward Euler scheme in a function growth_FE(N_0, dt, T)
as described in b).
d) Compare visually the solution produced by the Forward and Backward Euler
schemes with the exact solution when r = 1 and T = 6. Make two plots, one
with Δt = 0.5 and one with Δt = 0.05.
Filename: growth_BE.py.
Précédent

- 296/350

Suivant