You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Deriv包求导报错:Could not retrieve body of 'return()'原因咨询

报错原因与解决方法

报错原因

  • Deriv包的自动微分逻辑对分支结构中的**显式return()**支持不佳,无法正确提取return语句内的计算表达式进行微分解析。
  • 原函数else分支中的-log(0)属于无效数值操作,虽运行时会返回Inf,但会干扰Deriv的语法解析流程。

解决方法

  1. 移除显式的return()语句,R函数默认会返回最后一行计算的结果,Deriv可直接解析核心计算逻辑。
  2. 用Inf替代-log(0),符合R的数值规范,避免不必要的解析问题。
  3. (可选)改用向量式的ifelse写法,进一步简化函数结构,提升Deriv的解析兼容性。

修改后的函数(移除显式return)

f_current_theta <- function(current_theta) {
  if(current_theta > 0){
    -log(sqrt(2) * exp(-2*current_theta) / pi * sqrt(current_theta))
  } else {
    Inf
  }
}

更简洁的向量式写法

f_current_theta <- function(current_theta) {
  ifelse(current_theta > 0, 
         -log(sqrt(2) * exp(-2*current_theta) / pi * sqrt(current_theta)), 
         Inf)
}

执行求导

U_grad <- Deriv::Deriv(f_current_theta)

内容的提问来源于stack exchange,提问作者NoaMi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 19:52:03