简体   繁体   English

如何评估R中样条函数的导数?

[英]how can I evaluate the derivative of a spline function in R?

R can generate a spline function using splinefun() in the splines library. R可以使用样条库中的splinefun()生成样条函数。 However, I need to evaluate this function at its first and second derivatives. 但是,我需要对它的一阶和二阶导数进行评估。 Is there a way to do this? 有没有办法做到这一点?

for example 例如

library(splines)
x <- 1:10
y <- sin(pi/x) #just an example
f_of_x <- splinefun(x,y)

How can I evaluate f'(x) for a vector of x's? 如何评估x的向量的f'(x)?

It is very easy to do since the ability to evaluate the function at its derivatives is built in to the function! 这很容易做到,因为在函数中内置了评估函数的能力!

 f_of_x(x, deriv = 1)

Thanks R-core! 谢谢R-core!

您可能还对TeachingDemos软件包中的TkSpline函数感兴趣,该软件包将绘制样条函数及其派生函数。

The use of the deriv = argument to splinefun is sensible, and it should be added that second and third derivatives are supposed to be available, but if you work through the examples you will realize that the linear approximations are jagged and or discontinuous at higher degrees. 在splinefun上使用deriv =参数是明智的,应该添加二阶和三阶导数应该可用,但是如果您遍历示例,您将认识到线性近似在较高的程度上呈锯齿状或不连续。

In the situation in which you have an analytical expression there are some admittedly limited provisions for algorithmic differentiation. 在您具有解析表达式的情况下,有一些公认的有限算法区分规定。 See the help(deriv) page for more details. 有关更多详细信息,请参见帮助(派生)页面。

> 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
})

And then constructing "by hand" a second function with that result. 然后用该结果“手动”构造第二个功能。 Or you could use the DD example provided on the help(deriv) page to automate the process a bit more: 或者,您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM