【问题标题】:Finding root for Hermite spline寻找 Hermite 样条的根
【发布时间】:2019-05-03 02:25:53
【问题描述】:

寻找 Hermite 样条的根 我对 StackOverflow 中的一个讨论有疑问
get x-value given y-value: general root finding for linear / non-linear interpolation function

他们告诉我们,对于 stats::splinefun 使用“fmm”、“natrual”、“periodic”和“hyman”方法返回的三次插值样条曲线,函数 RootSpline3 提供了一个稳定的数值解。现在如果我使用“monoH.FC”,RootSpline3 函数会起作用吗?我实际上已经尝试过,但似乎它不起作用。你能说出我的代码有什么问题吗(为什么长度参数无效)?我的代码是错误的还是不适用于这种特定方法?如果是,我需要做什么?)。

kne<-c(10,15,18,18,15,14,13,13,15,21,26,39,52,64,70,66,57,40,22,11)
t<-seq(0,1,len=20)
s <- splinefun(t, kne, method = "monoH.FC")

RootSpline3 <- function (s, y0 = 0, verbose = TRUE) {
  ## extract piecewise construction info
  info <- environment(s)$z
  print(info)
  n_pieces <- info$n - 1L
  x <- info$x; y <- info$y
  print(x)
  b <- info$b; c <- info$c; d <- info$d
  ## list of roots on each piece
  xr <- vector("list", n_pieces)
  ## loop through pieces
  i <- 1L
  while (i <= n_pieces) {
    ## complex roots
    croots <- polyroot(c(y[i] - y0, b[i], c[i], d[i]))
    ## real roots (be careful when testing 0 for floating point numbers)
    rroots <- Re(croots)[round(Im(croots), 10) == 0]
    ## the parametrization is for (x - x[i]), so need to shift the roots
    rroots <- rroots + x[i]
    ## real roots in (x[i], x[i + 1])
    xr[[i]] <- rroots[(rroots >= x[i]) & (rroots <= x[i + 1])]
    ## next piece
    i <- i + 1L
  }
  ## collapse list to atomic vector
  xr <- unlist(xr)
  ## make a plot?
  if (verbose) {
    curve(f, from = x[1], to = x[n_pieces + 1], xlab = "x", ylab = "f(x)")
    abline(h = y0, lty = 2)
    points(xr, rep.int(y0, length(xr)))
  }
  ## return roots
  xr
}

RootSpline3(s, 10)

【问题讨论】:

  • 请提供minimal reproducible example。例如,Data 和 kne 未定义。你有没有可能有一些n_pieces 是NA?
  • @andrew_reece,我做了一个简单的随机示例来编辑问题,据我所知 n_pieces 应该是一个数字。虽然如果你尝试打印它,它会给出 NA,但我不明白为什么。

标签: r spline


【解决方案1】:

根据您使用的样条方法,您将获得不同的environment。在method = 'monoH.FC' 的情况下,没有可用的环境变量(如$z、$c、$d 等),因为默认样条方法('fmm')。

但是,仍然有一个 x 和 y 参数可以用 monoH.FC splinefun() 调用,这两个参数都会产生向量,并且可以用来绘制样条拟合。

使用您的数据:

s(kne)
# -1870 -14201  -3542  -3751  -2915  -2706  -2497  -3333  -2288  -4169  -5214 
# -7931 -10648 -13156 -14410 -13574 -11693  -8140  -4378  -2079
s(t)
# 10 69 18 19 15 14 13 17 12 21 26 39 52 64 70 66 57 40 22 11

plot(t, kne)
curve(s(x), add = TRUE)

【讨论】:

  • 实际上我的问题是如何为 y(函数值)找到 x 说 10?我试过“x[which(s(x) == 10)]”,但它给出了 NULL。
  • 我的意思是它为我们已经拥有的点提供了值,但没有为其他点提供值(它实际上完全有道理,因为我们没有进行逆插值)。我只是想知道为这种特定方法进行逆插值的任何方法。我是 R 新手,无法编写自己的反插值函数。
猜你喜欢
  • 2016-08-07
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
  • 2013-11-01
  • 1970-01-01
相关资源
最近更新 更多