8.6 Exercises
273
corresponding lists, so that convergence rates (r) can be computed after the loop.
Observe, in the loop, how ode_FE returns (the solution u and) the time mesh t,
which then is used as input to the u_exact function, causing the exact function
values to also be computed at the very same mesh points as u.
The Forward Euler method is a first order method, so we should get r near 1 as
the time step becomes small enough. A call to this test function does indeed confirm
(remove # in front of print(r)) that r comes very close to 1 as dt gets smaller.
8.6 Exercises
Exercise 8.1: Restructure a Given Code
Section 8.1.1 gives a code for computing the development of water volume V in
a tank. Restructure the code by introducing an appropriate function compute_V
that computes and returns the volumes, and a function application that calls the
former function and plots the result.
Note that your restructuring should not cause any change in program behavior,
as experienced by a user of the program.
Filename: restruct_tank_case1.py.
Exercise 8.2: Geometric Construction of the Forward Euler Method
Section 8.2.4 describes a geometric interpretation of the Forward Euler method.
This exercise will demonstrate the geometric construction of the solution in detail.
Consider the differential equation u = u with u(0) = 1. We use time steps Δt = 1.
a) Start at t = 0 and draw a straight line with slope u (0) = u(0) = 1. Go one time
step forward to t = Δt and mark the solution point on the line.
b) Draw a straight line through the solution point (Δt, u 1 ) with slope u (Δt) = u 1 .
Go one time step forward to t = 2Δt and mark the solution point on the line.
c) Draw a straight line through the solution point (2Δt, u 2 ) with slope u (2Δt) =
u 2 . Go one time step forward to t = 3Δt and mark the solution point on the line.
d) Set up the Forward Euler scheme for the problem u = u. Calculate u 1 , u 2 , and
u 3 . Check that the numbers are the same as obtained in a)-c).
Filename: ForwardEuler_geometric_solution.py.
Exercise 8.3: Make Test Functions for the Forward Euler Method
The purpose of this exercise is to make a file test_ode_FE.py that makes use
of the ode_FE function in the file ode_FE.py and automatically verifies the
implementation of ode_FE.
a) The solution computed by hand in Exercise 8.2 can be used as a reference
solution. Make a function test_ode_FE_1() that calls ode_FE to compute three
time steps in the problem u = u, u(0) = 1, and compare the three values u 1 , u 2 ,
and u 3 with the values obtained in Exercise 8.2.
b) The test in a) can be made more general using the fact that if f is linear in
u and does not depend on t, i.e., we have u = ru, for some constant r, the
Forward Euler method has a closed form solution as outlined in Sect. 8.2.1: u n =
U 0 (1 +rΔt) n . Use this result to construct a test function test_ode_FE_2() that
Précédent

- 293/350

Suivant