gpt4 book ai didi

r - 如何在R中创建斜率场?

转载 作者:行者123 更新时间:2023-12-04 16:08:01 24 4
gpt4 key购买 nike

我已经开始研究微分方程,我想绘制一些。

所以,假设我有 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)

但是如何绘制呢?

最佳答案

使用来自 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

关于r - 如何在R中创建斜率场?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47984874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com