How to compute the derivative of a function (in R)
Task
Given a mathematical function
Solution
Let’s consider the function
1
formula <- expression( 10*x^2 - 16*x + 1 )
We can compute its derivative using the D
function.
1
D( formula, "x" ) # derivative with respect to x
10 * (2 * x) - 16
R does not simplify the output, but if we do so ourselves, we find that
If it had been a multi-variable function, we would need to specify the variable with respect to which we wanted to compute a derivative.
1
2
formula2 <- expression( x^2-y^2 ) # consider the formula x^2 - y^2
D( formula2, "y" ) # differentiate with respect to y
-(2 * y)
That output says that
We can compute the second derivative by using the D
function twice
and specifying the variables with respect to which we are computing the derivative.
1
D( D( formula2, "x" ), "x" ) # second derivative with respect to x
[1] 2
1
D( D( formula2, "x" ), "y" ) # mixed partial derivative
[1] 0
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Debayan Sen (DSEN@bentley.edu)