[英]How can I get derivative value in R?
I want to get the derivative value from the function below when x = 2. Is there way to keep the form of the function and also get derivative value with out any additional package? 当x = 2时,我想从下面的函数中得到导数值。有没有办法保留函数的形式,并且在没有任何附加包的情况下获得衍生价值?
f <- function(x)
return(x^3)
For example, I have tried below but they didn't work. 例如,我在下面尝试过,但它们没有用。
x=2
deriv(~f, "x")
x=2
deriv(~body(f),"x")
x=2
D(expression(f),"x")
You can use deriv
, however, one caveat is that you can only use expressions/calls . 您可以使用deriv
,但有一点需要注意, 您只能使用表达式/调用 。
derivative = deriv(~ x^3, "x")
x <- 2
eval(derivative )
With a named expression: 使用命名表达式:
f = expression(x^3)
dx2x <- D(f,"x")
and the rest is the same. 其余的都是一样的。
See this link for the documentation: https://www.rdocumentation.org/packages/Deriv/versions/3.8.2/topics/Deriv 请参阅此链接以获取文档: https : //www.rdocumentation.org/packages/Deriv/versions/3.8.2/topics/Deriv
This would be approximation 这将是近似的
foo = function(x, delta = 1e-5, n = 3){
x = seq(from = x - delta, to = x + delta, length.out = max(2, n))
y = x^3
mean(diff(y)/diff(x))
}
foo(2)
#[1] 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.