进行更高效的蒙特卡罗模拟

时间:2012-11-19 01:50:05

标签: performance r statistics simulation

所以,我编写了这个代码,它应该有效地估计定义为h(x)的函数曲线下的面积。我的问题是我需要能够将区域估计到小数点后6位,但我在estimateN中定义的算法似乎对我的机器来说太重了。基本上问题是如何使以下代码更有效?有没有办法摆脱那个循环?

h = function(x) {
    return(1+(x^9)+(x^3))
}
estimateN = function(n) {
    count = 0
    k = 1
    xpoints = runif(n, 0, 1)
    ypoints = runif(n, 0, 3)
    while(k <= n){
    if(ypoints[k]<=h(xpoints[k]))
        count = count+1
    k = k+1
    }
    #because of the range that im using for y
    return(3*(count/n))
}
#uses the fact that err<=1/sqrt(n) to determine size of dataset
estimate_to = function(i) {
    n = (10^i)^2
    print(paste(n, " repetitions: ", estimateN(n)))
}

estimate_to(6)

2 个答案:

答案 0 :(得分:8)

替换此代码:

count = 0
k = 1
while(k <= n){
if(ypoints[k]<=h(xpoints[k]))
    count = count+1
k = k+1
}

这一行:

count <- sum(ypoints <= h(xpoints))

答案 1 :(得分:1)

如果你真正有效地努力,integrate对于这个问题来说要快几个数量级(更不用说内存效率更高)。

integrate(h, 0, 1)

# 1.35 with absolute error < 1.5e-14

microbenchmark(integrate(h, 0, 1), estimate_to(3), times=10)

# Unit: microseconds
#                expr        min         lq     median         uq        max neval
#  integrate(h, 0, 1)     14.456     17.769     42.918     54.514     83.125    10
#      estimate_to(3) 151980.781 159830.956 162290.668 167197.742 174881.066    10