Search code examples
rdifferential-equations

how to specify final value (rather than initial value) for solving differential equations


I would like to solve a differential equation in R (with deSolve?) for which I do not have the initial condition, but only the final condition of the state variable. How can this be done?

The typical code is: ode(times, y, parameters, function ...) where y is the initial condition and function defines the differential equation.


Solution

  • Are your equations time reversible, that is, can you change your differential equations so they run backward in time? Most typically this will just mean reversing the sign of the gradient. For example, for a simple exponential growth model with rate r (gradient of x = r*x) then flipping the sign makes the gradient -r*x and generates exponential decay rather than exponential growth.

    If so, all you have to do is use your final condition(s) as your initial condition(s), change the signs of the gradients, and you're done.

    As suggested by @LutzLehmann, there's an even easier answer: ode can handle negative time steps, so just enter your time vector as (t_end, 0). Here's an example, using f'(x) = r*x (i.e. exponential growth). If f(1) = 3, r=1, and we want the value at t=0, analytically we would say:

    x(T) = x(0) * exp(r*T) 
    x(0) = x(T) * exp(-r*T)
         = 3 * exp(-1*1)
         = 1.103638
    

    Now let's try it in R:

    library(deSolve)
    g <- function(t, y, parms) { list(parms*y) }
    res <- ode(3, times = c(1, 0), func = g, parms = 1)
    print(res)
    ##   time        1
    ## 1    1 3.000000
    ## 2    0 1.103639
    

    I initially misread your question as stating that you knew both the initial and final conditions. This type of problem is called a boundary value problem and requires a separate class of numerical algorithms from standard (more elementary) initial-value problems.

    library(sos)
    findFn("{boundary value problem}")
    

    tells us that there are several R packages on CRAN (bvpSolve looks the most promising) for solving these kinds of problems.