寻找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函数是否可以工作?我实际上已经尝试过了,但似乎不起作用。您能告诉我代码中有什么问题吗(为什么length参数无效)?我的代码是错误的还是对这种特定方法不起作用?如果是,我该怎么办?)。
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)