【发布时间】: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,但我不明白为什么。