2016-01-23 45 views
0

我想將函數M2_11(如下所示)整合到x上,對於固定的theta = c(2,0.8),c = 1.1,a=c(1,1)A = matrix(c(1/0.8,0.03,0.03,2/0.8),nrow=2,ncol=2)R中的「集成」功能給出了錯誤的結果

M2_11 = function(x, theta, c, a, A){ 
return((score1(x,theta)-a[1])^2* (weight(x, theta, c, a, A))^2 * f(x, theta)) 
} 

R的集成功能得出以下結果

theta = c(2,0.8) 
c = 1.1 
a=c(1,1) 
A = matrix(c(1/0.8,0.03,0.03,2/0.8),nrow=2,ncol=2) 
integrate(M2_11, lower = 1e-100, upper = 10 ,subdivisions = 10000, theta,c,a,A) 

0.0006459957絕對錯誤< 4.5E-05

做一體化的另一個方式給出了相同的結果

fM2_11 = function(x){M2_11(x,theta,c,a,A)} 
integrate(fM2_11, lower = 1e-100, upper = 10,subdivisions = 10000) 

0.0006459957絕對錯誤< 4.5E-05

結果的整合功能提供了,但是,顯然是錯誤的:

x = seq(1e-100,10,by=0.001) 
integrand = sapply(x,fM2_11) 

enter image description here

的區域下的曲線明顯大於0.00066

I還使用循環

loop_result = rep(NA,length(x)) 
for (i in 1:length(x)){ 
    loop_result[i] = M2_11(x[i],theta,c,a,A) 
} 
table(integrand==loop_result) 

TRUE

這是怎麼回事檢查結果?

+3

爲什麼'integrand = sapply(x,fM2_11)'而不是'fM2_11(x)'?我沒有深入瞭解代碼,但我想'fM2_11'可能不是矢量化的,而「集成」要求它是。閱讀「集成」。 – nicola

+0

謝謝尼古拉!我欠你一個人情! –

回答

1

非常感謝尼古拉。問題已經解決了。

integrate(Vectorize(fM2_11), lower = 1e-100, upper = 10 ,subdivisions = 10000) 

0.1588699與絕對誤差< 1.7E-07

sum(integrand)*0.001 

0.1588705

不要期待回答如此簡單!

+1

只是FYI,'Vectorize()'幾乎就是'mapply()'的包裝。在單一參數的情況下,單個結果函數將相當於'sapply()' –