Ordinary differential equations: Slope field and solution curves with R
Drawing a slope field with some integral curves<br/> [R worked-out solution]
We consider the differential equation
Assignments
- Determine the general solution of the differential equation in implicit form by the method of separation of variables.
- Draw a slope field and use the
geom_contour
function from theggplot2
package to draw some integral curves in it.
The result should resemble the figure below.
Worked-out solution
- We write the differential equation in differential form and apply separation of variables: When we integrate on both sides we get So: for some constant . In other words, where
- You are asked to draw a slope field and some integral curves in one diagram. The last aspect concerns the drawing of contours of The following code, in which the
ggplot2
anddplyr
packages are used, produces the diagram below:# load R packages
library(dplyr) library(ggplot2)
# prepare the computation of the slope field tp <- seq(from=-3, to=7, by=0.5) yp <- seq(from=-4, to=4, by=0.5) px <- c() py <- c() vx <- c() vy <- c() for(t in tp){ for(y in yp){ u <- 1.0 v <- (4.0-2.0*t)/(3.0*y^2-5.0) L <- sqrt(u*u+v*v) u <- u/L v <- v/L px <- c(px, t-0.15*u) py <- c(py, y-0.15*v) vx <- c(vx, 0.3*u) vy <- c(vy, 0.3*v) } } d <- data.frame(x=px, y=py, vx=vx, vy=vy)
# prepare the computation of the contour lines f <- function(t,y){ y^3-5*y+t^2-4*t } t <- seq(-3.5, 7.5, by=0.1) y <- seq(-4, 4, by=0.1) dat <- expand.grid(t = t, y = y) # make a grid for geom_countour dat <- mutate(dat, z = f(t, y)) # evaluate the function at each grid point
# draw the slope fiweld with integral curves ggplot(dat, aes(t, y)) + geom_contour(aes(z = z), binwidth=6, colour="blue", size=1) + theme(panel.background = element_rect(fill = "white", colour = "grey50")) + geom_segment(data=d, mapping=aes(x=px, y=py, xend=px+vx, yend=py+vy), colour="red")
The integral curves describe more than one solution curve. The outer integral curve does this for 3 solution curves that depend on an initial value. We distinguish as solution curves
- the top part with values greater than ;
- the middle part with values between and ;
- the lower part smaller than
Unlock full access