在 r 中找到函数的第 i 个导数的便捷方法?
Convenient way to find the i'th derivative of a function in r?
有没有一种方便的方法可以找到 r 中的(正态密度)函数的第 i 个导数?
是的,有。参见 help("D")
。
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)
}
ddnorm <- function(x) eval(DD(expression(dnorm(x)), "x", order = 1))
dddnorm <- function(x) eval(DD(expression(dnorm(x)), "x", order = 2))
curve(dnorm(x), -2, 2, ylim = c(-0.4, 0.4))
curve(ddnorm(x), -2, 2, add = TRUE, col = "dark red")
curve(dddnorm(x), -2, 2, add = TRUE, col = "dark blue")
legend(x = "topleft", legend = c("dnorm", "first derivative", "second derivative"),
col = c("black", "dark red", "dark blue"),
lty = 1)
有没有一种方便的方法可以找到 r 中的(正态密度)函数的第 i 个导数?
是的,有。参见 help("D")
。
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)
}
ddnorm <- function(x) eval(DD(expression(dnorm(x)), "x", order = 1))
dddnorm <- function(x) eval(DD(expression(dnorm(x)), "x", order = 2))
curve(dnorm(x), -2, 2, ylim = c(-0.4, 0.4))
curve(ddnorm(x), -2, 2, add = TRUE, col = "dark red")
curve(dddnorm(x), -2, 2, add = TRUE, col = "dark blue")
legend(x = "topleft", legend = c("dnorm", "first derivative", "second derivative"),
col = c("black", "dark red", "dark blue"),
lty = 1)