Tutorial 6: numeric solutions of ODEs
Objectives:
- Define a function that corresponds to an ODE
- Use the
deSolve
package to calculate numeric solutions of ODEs - Use functions to graph the defining functions of ODEs
- Pass function names to other functions (optional)
Numeric solution of differential equations
We will use the package deSolve
to calculate numeric solutions of ODEs. First, we need to create the R function that defines the derivative in the differential equation, in other words, the function \(f(x,t)\) in the generic first-order ODE
\[ \frac{dx}{dt} = f(x,t)\]
This R function must have three inputs: t
, x
, parms
, in that order, representing the time variable, the dependent variable x
, and the vector of parameters parms
. Let us illustrate this on the linear population model with birth rate b and death rate d:
\[ \frac{dN}{dt} = bN-dN \]
To solve this ODE with define the function that calculates the function on the right-hand-side (bN-dN). Notice that even though the function does not depend on time, t still must be the first input argument of the function:
The first two lines extract the two parameters b and d from the vector of parameter values, the next line calculate the value of the derivative, and the last one returns it.
Third, we assign the parameter values to the vector, create a time vector on which to solve the ODE, and assign the initial condition(s):
Finally, we are ready to call the function ode
that will do all the work to solve this ODE using the function pop_funk
:
The output
is a data frame, which means that you can use the data=
option in plot
to make your graph of the solution as a function of time:
This solution, like all numeric solutions of ODEs, is an approximation of the exact (analytic) solution. In this case, we can find (and verify) the exact solution of this model:
\[ N(t) = N(0)e^{(b-d)t}\]
Thus we can plot the analytic solution along with the numeric solution to see how far off they are:
You can see that the ODE solver is so clever that the numeric solution appears identical to the exact solution, even though there is always some degree of error in numeric solutions of ODEs.