Finding root for Hermite spline
I have a question regarding one discussion that already in StackOverflow
get x-value given y-value: general root finding for linear / non-linear interpolation function
They told that for cubic interpolation splines returned by stats::splinefun with methods "fmm", "natrual", "periodic" and "hyman", the function RootSpline3 provides a stable numerical solution. Now if I use "monoH.FC", would the RootSpline3 function work? I have actually tried it, but seems like it doesn't work. Can you tell what is wrong in my code(why the length argument is invalid)? Either my code is wrong or it will not work for this particular method? If yes, what I need to do?).
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)