如何在R中创建斜率场?

时间:2017-12-26 23:54:14

标签: r differential-equations

我已开始进入微分方程式,我想绘制一些。

所以,说我有dy / dx = -x / y,

如何获得这样的斜率字段:

slope field

我手动计算了我的数据并将其放在数据框中:

library(dplyr)

# creating data manually
x <- c(0, 1, 1, -1, 1)
y <- c(1, 1, 0, -1, -1)
slope <- c(0, -1, NaN, -1, 1)

# putting data in dataframe
data <- data_frame(x, y, slope)

但是如何绘制呢?

1 个答案:

答案 0 :(得分:2)

使用与 link 相同的想法并进行一些改进来控制箭头和网格点的大小:

SlopeField = function(FUN,xi = -5,xs = 5,yi = -5,ys = 5, radius = 0.1, grid.by = 0.25){
  # FUN   - given function ODE i.e:  
  # xi,xs - lower and upper bound - x - plot
  # yi,ys - lower and upper bound - y - plot
  
  # grid points
  seqx = seq(xi,xs,grid.by)
  seqy = seq(yi,ys,grid.by)
  
  # plot
  f = c(xi,xs) 
  h = c(yi,ys)
  plot(f,h,main="Slope field", ylab = "Dependet variable", xlab = "Independet variable", pch = ".")
  
  # arrows
  
  for(x in seqx){
    for(y in seqy){
      ym = y
      xm = x
      
      slope = unlist(FUN(x,y))
      
      if(is.na(slope)){
        cor = "black"
      } else if(slope > 0){
        cor = "blue"
      }else if (slope < 0) {
        cor = "red"
      }else if(slope == 0) {
        cor = "green"
      }
      arrows(radius*cos(atan(slope)+pi)+xm,
             radius*sin(atan(slope)+pi)+ym,
             radius*cos(atan(slope))+xm,
             radius*sin(atan(slope))+ym, 
             length = 0.2*radius, col= cor)
    }
  }
}

创建 ODE 函数:

ode = function(t, y){
  dydt <- y^2-t
  list(dydt)
}

函数结果:

SlopeField(ode, xi = -2, xs = 5, yi = -2, ys = 2,radius = 0.1, grid.by = 0.25)

enter image description here