【问题标题】:Trying to evaluate a function within a function numerically尝试以数值方式评估函数中的函数
【发布时间】:2014-06-28 14:31:00
【问题描述】:

这是我的代码:

L=function(t){
  n0=n2=1
  n1=1.5151
  A=function(theta){
    n0/(sqrt(n1^2-n2^2*(sin(theta))^2))*n2^2*sin(theta)*cos(theta)/(n1^2-n0*sqrt(n1^2-n2^2*(sin(theta))^2))
  }
  B=function(theta){
    -50/(cos(theta))^2*n1*n2*sin(theta)/(n1^2-n0*sqrt(n1^2-n2^2*(sin(theta))^2))
  }
  F=function(theta0){
    exp(integrate(A(theta),lower=0,upper=theta0))
  }

  1/(F(t))*(50+integrate(F(theta)*B(theta),lower=0,upper=t))
}

我正在尝试评估积分中的积分。所以我在函数中放置了一些虚拟变量,显然你现在可以这样做了。谁能帮我解决这个问题?谢谢。

【问题讨论】:

    标签: r integration numerical-integration


    【解决方案1】:

    integrate 函数需要一个函数作为其第一个参数,因此您只需传递类似 Afunction(x) F(x)*B(x) 的内容。错误消息“A(theta) 中的错误:找不到对象 'theta'”应该是有关此问题的提示。

    其次,integrate 函数返回integrate 类型的列表,因此您似乎需要value 该列表的元素。把它们放在一起:

    L=function(t){
      n0=n2=1
      n1=1.5151
      A=function(theta){
        n0/(sqrt(n1^2-n2^2*(sin(theta))^2))*n2^2*sin(theta)*cos(theta)/(n1^2-n0*sqrt(n1^2-n2^2*(sin(theta))^2))
      }
      B=function(theta){
        -50/(cos(theta))^2*n1*n2*sin(theta)/(n1^2-n0*sqrt(n1^2-n2^2*(sin(theta))^2))
      }
      F=function(theta0){
        exp(integrate(A,lower=0,upper=theta0)$value)
      }
    
      1/(F(t))*(50+integrate(function(x) F(x)*B(x),lower=0,upper=t)$value)
    }
    L(1)
    # [1] -19.33926
    

    【讨论】:

      【解决方案2】:

      这里有几个问题。首先exp(integrate(A(theta),lower=0,upper=theta0)) 不起作用,因为integrate 返回一个列表。您需要使用$value 访问积分的值。

      其次,integral的第一个参数必须是函数,而不是函数值,所以integrate(A(theta),lower=0,upper=theta0)应该是integrate(A,lower=0,upper=theta0),和F*B的积分一样。做出这些改变我得到了

      L=function(t){
        n0=n2=1
        n1=1.5151
        B=function(theta){
          -50/(cos(theta))^2*n1*n2*sin(theta)/(n1^2-n0*sqrt(n1^2-n2^2*(sin(theta))^2))
        }
        F=function(theta0){
          A<-function(theta){
            n0/(sqrt(n1^2-n2^2*(sin(theta))^2))*n2^2*sin(theta)*cos(theta)/(n1^2-n0*sqrt(n1^2-n2^2*(sin(theta))^2))
          }
          exp(integrate(A,lower=0,upper=theta0)$value)
        }
      
        1/(F(t))*(50+integrate(function(x) F(x)*B(x),lower=0,upper=t)$value)
      }
      

      哪个运行,例如

      > L(.5)
      [1] 33.4549
      

      我相信你会想要合理地检查这个答案。

      【讨论】:

      • 我想你会想要运行L(10),这给了我“exp(integrate(A, lower = 0, upper = theta0)) 中的错误:数学函数的非数字参数”,因为您还没有使用$value 提取值。
      • 谢谢,现已修复。 L(10) 似乎没有收敛。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      • 2018-07-31
      • 2011-04-26
      • 2015-01-17
      相关资源
      最近更新 更多