在 R 编程中计算表达式的导数 - deriv() 和 D()函数
在 R 编程中,可以使用deriv()
和D()
函数计算函数的导数。它用于计算简单表达式的导数。
Syntax:
deriv(expr, name)
D(expr, name)
Parameters:
expr: represents an expression or a formula with no LHS
name: represents character vector to which derivatives will be computed
示例 1:
# Expression or formula
f = expression(x^2 + 5*x + 1)
# Derivative
cat("Using deriv() function:\n")
print(deriv(f, "x"))
cat("\nUsing D() function:\n")
print(D(f, 'x'))
输出:
Using deriv() function:
expression({
.value <- x^2 + 5 * x + 1
.grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
.grad[, "x"] <- 2 * x + 5
attr(.value, "gradient") <- .grad
.value
})
Using D() function:
2 * x + 5
示例 2:
# Little harder derivative
# Using deriv() Function
cat("Using deriv() function:\n")
print(deriv(quote(sinpi(x^2)), "x"))
# Using D() Function
cat("\nUsing D() function:\n")
print(D(quote(sinpi(x^2)), "x"))
输出:
Using deriv() function:
expression({
.expr1