Search code examples
rdifferential-equations

Can R language find a generic solution of the first order differential equation?


Can R language find a generic solution of the first order differential equation?

For example:

(5x-6)^2 y' = 5(5x-6) y - 2 

PS:
That can be easily solved by hand, i.e. particular solution is:

y = 1/(5(5x-6))

and generic

C*(5x-6)

I need to understand whether R can do it?


Solution

  • We can use the R library deSolve to obtain numerical solutions of ODEs. See ?deSolve for details.

    Here is a worked-through example based on your ODE.

    1. Load the R library

      library(deSolve);
      
    2. Define the differential equation

      # Define the function
      f <- function(x, y, params) list((5 * (5 * x - 6) * y - 2) / (5 * x - 6)^2)
      
    3. Set x values for which to solve and initial condition

      # x values for which to solve
      x <- seq(2, 10, length.out = 100);
      
      # Initial value y(x=2) = 1/20
      y0 <- 1/20
      
    4. Solve the ODE

      # Solve ODE
      df <- as.data.frame(ode(y0, x, f, parms = NULL));
      
    5. Plot theoretical (algebraic) solution and numerical solution from deSolve

      # Plot
      library(ggplot2);
      ggplot(df, aes(time, `1`)) +
          stat_function(
              fun = function(x) 1/(5 * (5 * x - 6)),
              aes(colour = "Theoretical"),
              size = 4) +
          geom_line(aes(colour = "deSolve"), size = 2) +
          labs(x = "x", y = "y")
      

    enter image description here