11

R 可以使用 spline 库中的 splinefun() 生成样条函数。但是,我需要评估这个函数的一阶和二阶导数。有没有办法做到这一点?

例如

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

如何评估 x 向量的 f'(x)?

4

3 回答 3

18

这很容易做到,因为在函数中内置了对函数求导的能力!

 f_of_x(x, deriv = 1)

谢谢R核!

于 2010-12-02T19:41:52.237 回答
2

您可能还对 TeachingDemos 包中的 TkSpline 函数感兴趣,它将绘制样条函数及其导数。

于 2010-12-02T20:17:02.633 回答
2

对 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.
于 2010-12-02T20:25:55.480 回答