Docsity

Solving Sequences and ODE Systems: Difference vs. Ordinary Differential Equations, Study Guides, Projects, Research of Differential Equations

Partial preview of the text

Download Solving Sequences and ODE Systems: Difference vs. Ordinary Differential Equations and more Study Guides, Projects, Research Differential Equations in PDF only on Docsity!

Joakim Sundnes

Solving Ordinary Differential

Equations in Python

Nov 8, 2020

∗ Simula Research Laboratory and Department of Informatics, University of Oslo.

vi

ward Euler scheme to an ODE effectively turns the differential equation into a difference equation. If we already know how to program difference equa- tions it is therefore very easy to solve an ODE, by simply adding one extra step at the start of the process. However, although this structure provides a natural step-by-step introduction to ODE programming, it is entirely possi- ble to skip Chapter 1 completely and jump straight into the programming of ODE solvers in Chapter 2.

August 2020 Joakim Sundnes

Contents

  • 1 Programming of difference equations Preface v
    • 1.1 Sequences and Difference Equations
    • 1.2 Systems of Difference Equations
    • 1.3 More Examples of Difference Equations
    • 1.4 Taylor Series and Approximations
  • 2 Solving ordinary differential equations
    • 2.1 Creating a general-purpose ODE solver
    • 2.2 The ODE solver implemented as a class
    • 2.3 Alternative ODE solvers
    • 2.4 A class hierarchy of ODE solvers
  • 3 Solving systems of ODEs
    • 3.1 An ODESolver class for systems of ODEs
  • 4 Modeling infectious diseases
    • 4.1 Derivation of the SIR model
    • 4.2 Extending the SIR model
    • 4.3 A model of the Covid19 pandemic

Chapter 1

Programming of difference equations

Although the main focus of these notes is on solvers for differential equations , this first chapter is devoted to the closely related class of problems known as difference equations. The main motivation for introducing this topic first is that the mathematical formulation of difference equations is very easy to translate into a computer program. When we move on to ODEs in the next chapter, we shall see that such equations are typically solved by applying some numerical scheme to turn the differential equation into a difference equation, which is then solved using the techniques presented in this chapter.

1.1 Sequences and Difference Equations

Sequences is a central topic in mathematics, which has important applications in numerical analysis and scientific computing. In the most general sense, a sequence is simply a collection of numbers:

x 0 , x 1 , x 2 ,... , xn,....

For some sequences we can derive a formula that gives the the n -th number xn as a function of n. For instance, all the odd numbers form a sequence

1 , 3 , 5 , 7 ,... ,

and for this sequence we can write a simple formula for the n -th term;

xn = 2 n + 1_._

With this formula at hand, the complete sequence can be written on a com- pact form; ( xn )∞ n =0 , xn = 2 n + 1_._

1

2 1 Programming of difference equations

Other examples of sequences include

1 , 4 , 9 , 16 , 25 ,... ( xn )∞ n =0 , xn = n^2 ,

1 ,

,... ( xn )∞ n =0 , xn =

n + 1

1 , 1 , 2 , 6 , 24 ,... ( xn )∞ n =0 , xn = n! ,

1 , 1 + x, 1 + x +

x^2 , 1 + x +

x^2 +

x^3 ,... ( xn )∞ n =0 , xn =

∑^ n

j =

xj j!

These are all formulated as inifite sequences, which is common in mathemat- ics, but in real-life applications sequences are usually finite: ( xn ) Nn =0. Some familiar examples include the annual value of a loan or an investment. In many cases it is impossible to derive an explicit formula for the entire sequence, and xn is instead given by a relation involving xn − 1 and possibly xn − 2. Such equations are called difference equations , and they can be chal- lenging to solve with analytical methods, since in order to compute the n -th term of a sequence we need to compute the entire sequence x 0 , x 1 ,... , xn − 1. This can be very tedious to do by hand or using a calculator, but on a com- puter the equation is easy to solve with a for-loop. Combining sequences and difference equations with programming therefore enables us to consider far more interesting and useful cases.

A difference equation for computing interest. To start with a simple example, consider the problem of computing how an invested sum of money grows over time. In its simplest form, this problem can be written as putting x 0 money in a bank at year 0, with interest rate p percent per year. What is then the value after n years? You may recall from earlier in IN1900 (and from high school mathematics) that the solution to this problem is given by the simple formula xn = x 0 (1 + p/ 100) n,

so there is really no need to formulate and solve the problem as a difference equation. However, very simple generalizations, such as a non-constant in- terest rate, makes this formula difficult to apply, while a formulation based on a difference equation will still be applicable. To formulate the problem as a difference equation, we use the fact that the amount xn at year n is simply the amount at year n − 1 plus the interest for year n − 1. This gives the following relation between xn and xn − 1 :

xn = xn − 1 +

p 100

xn − 1_._

In order to compute xn , we can now simply start with the known x 0 , and compute x 1 , x 2 ,... , xn. The procedure involves repeating a simple calculation many times, which is tedious to do by hand, but very well suited for a com-

4 1 Programming of difference equations

Assuming that the rest of the code is unchanged from the example above, the loop variable n will run from 1 to 4. If we first insert the lower bound n= into the formula, we find that the first pass of the loop will try to compute x[2] from x[1]. However, we have only initialized x[0], so x[1] is zero, and therefore x[2] and all subsequent values will be set to zero. Furthermore, if we insert the upper bound n=4 we see that the formula will try to access x[5], but this does not exist and we get an IndexError. Performing such simple analysis of a for-loop is often a good way to reveal the source of the error and give an idea of how it can be fixed.

Solving a difference equation without using arrays. The program above stored the sequence as an array, which is a convenient way to program the solver and enables us to plot the entire sequence. However, if we are only interested in the solution at a single point, i.e., xn , there is no need to store the entire sequence. Since each xn only depends on the previous value xn − 1 , we only need to store the last two values in memory. A complete loop can look like this:

x_old = x for n in index_set[1:]: x_new = x_old + (p/100.)*x_old x_old = x_new # x_new becomes x_old at next step print (’Final amount: ’, x_new)

For this simple case we can actually make the code even shorter, since x_old is only used in a single line and we can just as well overwrite it once it has been used:

x = x0 #x is here a single number, not array for n in index_set[1:]: x = x + (p/100.)*x print (’Final amount: ’, x)

We see that these codes store just one or two numbers, and for each pass through the loop we simply update these and overwrite the values we no longer need. Although this approach is quite simple, and we obviously save some memory since we do not store the complete array, programming with an array x[n] is usually safer, and we are often interested in plotting the entire sequence. We will therefore mostly use arrays in the subsequent examples.

Extending the solver for the growth of money. Say we are interested in changing our model for interest rate, to a model where the interest is added every day instead of every year. The interest rate per day is r = p/D if p is the annual interest rate and D is the number of days in a year. A common model in business applies D = 360, but n counts exact (all) days. The difference equation relating one day’s amount to the previous is the same as above

xn = xn − 1 +

r 100

xn − 1 ,

1.1 Sequences and Difference Equations 5

except that the yearly interest rate has been replaced by the daily ( r ). If we are interested in how much the money grows from a given date to another we also need to find the number of days between those dates. This calculation could of course be done by hand, but Python has a convenient module named datetime for this purpose. The following session illustrates how it can be used:

import datetime date1 = datetime.date(2017, 9, 29) # Sep 29, 2017 date2 = datetime.date(2018, 8, 4) # Aug 4, 2018 diff = date2 - date print (diff.days) 309

Putting these tools together, a complete program for daily interest rates may look like

import numpy as np import matplotlib.pyplot as plt import datetime

x0 = 100 # initial amount p = 5 # annual interest rate r = p/360.0 # daily interest rate

date1 = datetime.date(2017, 9, 29) date2 = datetime.date(2018, 8, 4) diff = date2 - date N = diff.days index_set = range (N+1) x = np.zeros( len (index_set))

x[0] = x for n in index_set[1:]: x[n] = x[n-1] + (r/100.0)*x[n-1]

plt.plot(index_set, x) plt.xlabel(’days’) plt.ylabel(’amount’) plt.show()

This program is slightly more sophisticated than the first one, but one may still argue that solving this problem with a difference equation is unnecessarily complex, since we could just apply the well-known formula xn = x 0 (1 + 100 r ) n to compute any xn we want. However, we know that interest rates change quite often, and the formula is only valid for a constant r. For the pro- gram based on solving the difference equation, on the other hand, only minor changes are needed in the program to handle a varying interest rate. The simplest approach is to let p be an array of the same length as the number of days, and fill it with the correct interest rates for each day. The modifications to the program above may look like this:

1.3 More Examples of Difference Equations 7

xn = xn − 1 +

p 100

xn − 1 − cn − 1 ,

cn = cn − 1 +

I

cn − 1_._

with initial conditions x 0 = F and c 0 = ( pF/ 100)( q/ 100) = 10000 pF q. This is a coupled system of two difference equations, but the programming is not much more difficult than for the single equation above. We simply create two arrays x and c, initialize x[0] and c[0] to the given initial conditions, and then update x[n] and c[n] inside the loop. A complete code may look like

import numpy as np import matplotlib.pyplot as plt F = 1e7 # initial amount p = 5 # interest rate I = 3 q = 75 N = 40 # number of years index_set = range (N+1) x = np.zeros( len (index_set)) c = np.zeros_like(x)

x[0] = F c[0] = qpF*1e-

for n in index_set[1:]: x[n] = x[n-1] + (p/100.0)x[n-1] - c[n-1] c[n] = c[n-1] + (I/100.0)c[n-1]

plt.plot(index_set, x, ’ro’,label = ’Fortune’) plt.plot(index_set, c, ’go’, label = ’Yearly consume’) plt.xlabel(’years’) plt.ylabel(’amounts’) plt.legend() plt.show()

1.3 More Examples of Difference Equations

As noted above, sequences, series, and difference equations have countless applications in mathematics, science, and engineering. Here we present a selection of well known examples.

Fibonacci numbers as a difference equation. The sequence defined by the difference equation

xn = xn − 1 + xn − 2 , x 0 = 1 , x 1 = 1_._

8 1 Programming of difference equations

is called the Fibonacci numbers. It was originally derived for modeling rat populations, but it has a range of interesting mathematical properties and has therefore attracted much attention from mathematicians. The equation for the Fibonacci numbers differs from the previous ones, since xn depends on the two previous values ( n − 1 , n − 2 ), which makes this a second order difference equation. This classification is important for mathematical solution techniques, but in a program the difference between first and second order equations is small. A complete code to solve the difference equation and generate the Fibonacci numbers can be written as

import sys from numpy import zeros

N = int (sys.argv[1]) x = zeros(N+1, int ) x[0] = 1 x[1] = 1 for n in range (2, N+1): x[n] = x[n-1] + x[n-2] print (n, x[n])

Notice that in this case we need to initialize both x[0] and x[1] before start- ing the loop, since the update formula involves both x[n-1] and x[n-2]. This is the main difference between this second order equation and the pro- grams for first order equations considered above. The Fibonacci numbers grow quickly and running this program for large N will lead to problems with overflow (try for instance N = 100). The NumPy int type supports up to 9223372036854775807, which is almost 1019 , so this is very rarely a prob- lem in practical applications. We can fix the problem by avoiding NumPy arrays and instead use the standard Python int type, but we will not go into these details here.

Logistic growth. If we return to the initial problem of calculating growth of money in a bank, we can write the classical solution formula more compactly as xn = x 0 (1 + p/ 100) n^ = x 0 Cn^ (= x 0 en^ ln^ C^ ) ,

with C = (1 + p/ 100). Since n counts years, this is an example of exponential growth in time, with the general formula x = x 0 eλt. Populations of humans, animals, and other organisms also exhibit the same type of growth when there are unlimited resources (space and food), and the model for expo- nential growth therefore has many applications in biology.^2 However, most environments can only support a finite number R of individuals, while in the exponential growth model the population will continue to grow indefinitely.

(^2) The formula x = x 0 eλt (^) is the solution of the differential equation dx/dt = λx , and this formulation may be more familiar to some readers. As mentioned at the start of the chapter, differential equations and difference equations are closely related, and these relations are discussed in more detail in Chapter 2.

10 1 Programming of difference equations

Note that the logistic growth model is more commonly formulated as an ordinary differential equation (ODE), and we will consider this formulation in the next chapter. For certain choices of numerical method and discretization parameters, the program for solving the ODE is identical to the program for the difference equation considered here.

0 25 50 75 100 125 150 175 200 Time units

100

150

200

250

300

350

400

450

500

Population

Fig. 1.1 Solution of the logistic growth model for x 0 = 100 , ρ = 5_._ 0 , R = 500.

The factorial as a difference equation. The factorial n! is defined as

n! = n ( n − 1)( n − 2) · · · 1 , 0! = 1 (1.1)

The following difference equation has xn = n! as solution and can be used to compute the factorial: xn = nxn − 1 , x 0 = 1

As above, a natural question to ask is whether such a difference equation is very useful, when we can simply use the formula (1.1) to compute the factorial for any value of n. One answer to this question is that in many applications, some of which will be considered below, we need to compute the entire sequence of factorials xn = n! for n = 0 ,... N. We could still apply (1.1) to compute each one, but it involves a lot of redundant computations, since we perform n multiplications for each new xn. When solving the difference equation, each new xn requires only a single multiplication, and for large values of n this may speed up the program considerably.

Newton’s method as a difference equation. Earlier in the course we introduced Newton’s method for solving non-linear equations on the form

f ( x ) = 0

1.4 Taylor Series and Approximations 11

Starting from some initial guess x 0 , Newton’s method gradually improves the approximation by iterations

xn = xn − 1 −

f ( xn − 1 ) f ′( xn − 1 )

We may now recognize this as nonlinear first-order difference equation. As n → ∞, we hope that xn → xs , where xs is the solution to f ( xs ) = 0. In practice we solve the equation for n ≤ N , for some finite N , just as for the difference equations considered earlier. But how do we choose N so that xN is sufficiently close to the true solution xs? Since we want to solve f ( x ) = 0 , the best approach is to solve the equation until f ( x ) ≤  , where  is a small tolerance. In practice, Newton’s method will usually converge rather quickly, or not converge at all, so setting some upper bound on the number of iterations is a good idea. A simple implementation of Newton’s method as a Python function may look like

def Newton(f, dfdx, x, epsilon=1.0E-7, max_n=100): n = 0 while abs (f(x)) > epsilon and n <= max_n: x = x - f(x)/dfdx(x) n += 1 return x, n, f(x)

The arguments to the function are Python functions f and dfdx implementing f ( x ) and its derivative. Both of these arguments are called inside the function and must therefore be callable. The x argument is the initial guess for the solution x , and the two optional arguments at the end are the tolerance and the maximum number of iteration. Although the method is implemented as a while-loop rather than a for-loop, the main structure of the algorithm is exactly the same as for the other difference equations considered earlier.

1.4 Taylor Series and Approximations

One extremely important use of sequences and series is for approximating other functions. For instance, commonly used functions such as sin x, ln x , and ex^ have been defined to have some desired mathematical properties, but we need some kind of algorithm to evaluate the function values. A convenient approach is to approximate sin x , etc. by polynomials, since they are easy to calculate. It turns out that such approximations exist, for example this result by Gregory from 1667:

sin x =

∑^ ∞

k =

(−1) k^

x^2 k + (2 k + 1)!

1.4 Taylor Series and Approximations 13

If we now define en as the approximation with n terms, i.e. for k = 0 ,... , n − 1 , we have

en =

n ∑− 1

k =

xk k!

n ∑− 2

k =

xk k!

xn −^1 ( n − 1)!

and we can formulate the sum in en as the difference equation

en = en − 1 +

xn −^1 ( n − 1)!

, e 0 = 0_._ (1.3)

We see that this difference equation involves ( n − 1)!, and computing the complete factorial for every iteration involves a large number of redundant multiplications. Above we introduced a difference equation for the factorial, and this idea can be utilized to formulate a more efficient computation of the Taylor polynomial. We have that

xn n!

xn −^1 ( n − 1)!

x n

and if we let an = xn/n! it can be computed efficiently by solving

an = an − 1

x n

, a 0 = 1_._

Now we can formulate a system of two difference equations for the Taylor polynomial, where we update each term via the an equation and sum the terms via the en equation:

en = en − 1 + an − 1 , e 0 = 0 ,

an =

x n

an − 1 , a 0 = 1_._

Although we are here solving a system of two difference equations, the com- putation is far more efficient than solving the single equation in (1.3) directly, since we avoid the repeated multiplications involved in the factorial compu- tation. A complete Python code for solving the difference equation and compute the Taylor approximation to the exponential function may look like

import numpy as np

x = 0.5 #approximate exp(x) for x = 0.

N = 5 index_set = range (N+1) a = np.zeros( len (index_set)) e = np.zeros( len (index_set)) a[0] = 1

14 1 Programming of difference equations

print (f’Exact: exp({x}) = {np.exp(x)}’) for n in index_set[1:]: e[n] = e[n-1] + a[n-1] a[n] = x/n*a[n-1] print (f’n = {n}, approx. {e[n]}, error = {np.abs(e[n]-np.exp(x)):4.5f}’)

Exact: exp(0.5) = 1. n = 1, approx. 1.00000, error = 0. n = 2, approx. 1.50000, error = 0. n = 3, approx. 1.62500, error = 0. n = 4, approx. 1.64583, error = 0. n = 5, approx. 1.64844, error = 0.

This small program first prints the exact value ex^ for x = 0_._ 5 , and then the Taylor approximation and associated error for n = 1 to n = 5. The Taylor series approximation is most accurate close to x = 0, so choosing a larger value of x leads to larger errors, and we need to also increase n for the appoximation to be accurate.