问题
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?
回答1:
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.
Load the R library
library(deSolve);
Define the differential equation
# Define the function f <- function(x, y, params) list((5 * (5 * x - 6) * y - 2) / (5 * x - 6)^2)
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
Solve the ODE
# Solve ODE df <- as.data.frame(ode(y0, x, f, parms = NULL));
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")
来源:https://stackoverflow.com/questions/50229410/can-r-language-find-a-generic-solution-of-the-first-order-differential-equation