r - 变量中导数 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))
提前谢谢了!
解决方案
您可以构造一个以派生表达式为主体的函数:
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)
推荐阅读
- java - Java:如何将文件从 Windows 移动到 linux 服务器?
- c++ - 使用 unique_ptr 作为值初始化 const static std::map
- android - 在包含 CollapsingToolbarLayout 的 AppBarLayout 顶部时,MovableFloatingActionButton 不接收 onTouch
- matlab - 自动向下滚动列表框
- typescript - 打字稿克隆对象无法正常工作
- c++ - 试图在c++中做一个简单的加法器。编译成功但输出错误
- java - Google Sheets API 在一份申请中发送多个数据
- node.js - 特定软件包的纱线忽略引擎
- mysql - 批量插入 - 根据另一列的已知值创建一些列的值
- javascript - 匹配一个空对象数组