[英]how can I evaluate the derivative of a spline function in R?
R可以使用樣條庫中的splinefun()生成樣條函數。 但是,我需要對它的一階和二階導數進行評估。 有沒有辦法做到這一點?
例如
library(splines)
x <- 1:10
y <- sin(pi/x) #just an example
f_of_x <- splinefun(x,y)
如何評估x的向量的f'(x)?
這很容易做到,因為在函數中內置了評估函數的能力!
f_of_x(x, deriv = 1)
謝謝R-core!
您可能還對TeachingDemos軟件包中的TkSpline函數感興趣,該軟件包將繪制樣條函數及其派生函數。
在splinefun上使用deriv =參數是明智的,應該添加二階和三階導數應該可用,但是如果您遍歷示例,您將認識到線性近似在較高的程度上呈鋸齒狀或不連續。
在您具有解析表達式的情況下,有一些公認的有限算法區分規定。 有關更多詳細信息,請參見幫助(派生)頁面。
> deriv(~sin(pi/x), "x")
expression({
.expr1 <- pi/x
.value <- sin(.expr1)
.grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
.grad[, "x"] <- -(cos(.expr1) * (pi/x^2))
attr(.value, "gradient") <- .grad
.value
})
然后用該結果“手動”構造第二個功能。 或者,您可以使用help(deriv)頁面上提供的DD示例來自動化該過程:
DD <- function(expr,name, order = 1) {
if(order < 1) stop("'order' must be >= 1")
if(order == 1) D(expr,name)
else DD(D(expr, name), name, order - 1)
}
DD(expression(sin(pi/x)), "x", 2)
-(sin(pi/x) * (pi/x^2) * (pi/x^2) - cos(pi/x) * (pi * (2 * x)/(x^2)^2))
DD(expression(sin(pi/x)), "x")
-(cos(pi/x) * (pi/x^2))
funD<- function(x){}
body(funD) <- DD(expression(sin(pi/x)), "x")
funD
#function (x)
#-(cos(pi/x) * (pi/x^2))
funD(2)
# [1] -4.809177e-17 as it should be at a maximum
funDD <- function(x){}
body(funDD) <- DD(expression(sin(pi/x)), "x", 2)
funDD(2)
# [1] -0.6168503 as it should be at a maximum.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.