首页 > 解决方案 > 变量中导数 D() 的 uniroot()(或如何将对象编写为函数)

问题描述

我有一个简短的问题,希望有人可以帮助我。我找不到解决办法...

我想使用 uniroot() 来找到函数的零点,或者更精确地从函数的导数中找到。如果我将函数写为 function(x).. 这没问题,但如果我想通过变量将派生带到 uniroot,它不会。

#This will not work:
deriv1 <- D(expression(x^2-2*x),"x")
uniroot(deriv1, c(0,5))

# This will work:
func <- function(x) 2 * x - 2
uniroot(func, c(0,5))

提前谢谢了!

标签: r

解决方案


您可以构造一个以派生表达式为主体的函数:

deriv1 <- D(expression(x^2-2*x),"x")
f <- function(x){}
body(f) <- deriv1
uniroot(f, c(0,5))

您也可以使用符号演算代替uniroot

library(Ryacas)
fun <- yac_symbol("x^2-2*x")
dfun <- deriv(fun, "x")
solve(dfun, "x")
# {x==1} 

并提取解决方案:

yac_solution <- solve(dfun, "x")
solution <- yac_symbol(paste0("x Where ", solution))
yac(solution)

推荐阅读