-1

我正在尝试将非线性函数拟合到给定的数据集(代码片段中的 x 和 y),该函数定义为

f(x) = a/((sin((x-b)/2))^4)
x <- c(0, 5, -5, 10, -10, 15, -15, 20, -20, 25, -25, 30, -30)
y <- c(4.21, 3.73, 2.08, 1.1, 0.61, 0.42, 0.13, 0.1, 0.04, 0.036667, 0.016667, 0.007778, 0.007778)
plot(x,y, log="y")

这就是在提到函数之前我应该​​拟合的初始图的样子。

初始图

但是当我尝试使用 nls 拟合并绘制曲线时,该图看起来不太正确

f <- function(x,a,b) { a/((sin((x-b)/2))^4) }
fitmodel <- nls (y ~ f(x,a,b), start=list(a=1,b=1))
lines(x, predict(fitmodel))

这就是我所看到的:

绘制曲线

我很确定我在这里做错了什么,并感谢您的帮助。

4

1 回答 1

0

R 解释器完全按照您的要求执行。

x是未排序的数组。

因此,predict(fitmodel)对这些未排序的点进行预测。

lines(x, predict(fitmodel))按给定顺序连接点。它将 (x[1], predict(fitmodel)[1]) 连接到 (x[2], predict(fitmodel)[2]) 到 (x[3], predict(fitmodel)[3]) 等。点不按 x 排序,您可以在图中看到图片。

你可以ind <- order(x); x <- x[ind]; y <- y[ind]按照李哲元的建议去做。

此外,您的模型毫无意义。

f <- function(x,a,b) { a/((sin((x-b)/2))^4) }
fitmodel <- nls (y ~ f(x,a,b), start=list(a=1,b=1))

对于任何abf将是一个周期为 2π 的周期函数,而您的 x 在步骤 5 中从 -30 变为 30。您无法用这样的函数合理地近似您的点。

于 2016-11-03T23:04:41.537 回答