如何计算R中的双重积分

Roh*_*han 18 integration regression r

这是我的r代码,用于计算每种情况的beta值,这非常简单

data =data.frame(
  "t" = seq(0, 1, 0.001)
)


B3t <- function(t){
  t**3 - 1.6*t**2 +0.76*t+1
}

B2t <- function(t){

  ifelse(t >= 0 & t < 0.342,
         ((t-0.5)^2-0.025),

         ifelse( data$t >=  0.342 & data$t <= 0.658, 
                 0,

                 ifelse(t >  0.658 & t <= 1, 
                        (-(t-0.5)^2+0.025),
                        0
                 )))

}

B1t <- function(t){
  0
}


X1t <- function(t){
  a0 = rnorm(1)
  a1 = rnorm(1)
  a2 = rnorm(1)
  a3 = rnorm(1)

  return(a0 + a1*t + a2*(t^2) + a3*(t^3))
}

X2t <- function(t){
  a0 = rnorm(1)
  a1 = rnorm(1)
  a2 = rnorm(1)
  a3 = rnorm(1)
  a4 = rnorm(1)

  return(a0 + a1 * sin(2*pi*t) + a2 * cos(2*pi*t) + a3 * sin(4*pi*t) + a4 * cos(4*pi*t))
}
Run Code Online (Sandbox Code Playgroud)

现在我要计算误差项。

我有一个问题:有人可以帮我解决这个问题吗?

  1. 我如何解决双重积分以便计算误差项。

我知道r中有要执行的功能,integrate但是我不确定如何在这里实现它。

我正在尝试做下面提到的功能数据分析问题:

在此处输入图片说明 在此处输入图片说明

我不知道如何找到方差,以便找到遵循正态分布N(0,方差)的误差项

在此处输入图片说明

cit*_*ose 7

这是我的操作方法(对于Beta和X的一个版本)。请注意,双积分只是彼此嵌套的两个单积分。一个参数n定义了我用来估计积分中期望值的随机样本数。

beta <- function(t){
    return(t*t*t-1.6*t*t+0.76*t+1)
}

myX <- function(a,t){
    pt <- c(1,t,t*t,t*t*t)
    return(sum(a*pt))
}

## computes the expectation by averaging over n samples
myE <- function(n,s,t){
    samp <- sapply(seq(n),function(x){
          a <- rnorm(4)
          myX(a,s)*myX(a,t)})
    return(mean(samp,na.rm=T))
}

## funtion inside the first integral
myIntegrand1 <- function(s,t,n){
   return(beta(s)*myE(n,s,t))
}

## function inside the second integral
myIntegrand2 <- function(t,n){
    v <- integrate(myIntegrand1,0,1,t=t,n=n)
    return(beta(t)*v$value)
}

## computes sigma
mySig <- function(n){
  v <- integrate(myIntegrand2,0,1,n=n)
  return( 0.25*v$value)
}
## tests various values of n (number of samples drawn to compute the expectation)
sapply(seq(3),function(x)
             c("100"=mySig(100),"1000"=mySig(1000),"10000"=mySig(10000)))
## output shows you the level of precision you may expect:
##       [,1]     [,2]     [,3]
##  100  48.61876 47.85445 58.2094
## 1000  52.95681 50.61860 50.61702
## 10000 54.88292 53.02073 54.48635
Run Code Online (Sandbox Code Playgroud)