5

因此,我编写了这段代码,它应该有效地估计定义为 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)
4

2 回答 2

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))
于 2012-11-19T02:01:44.337 回答
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
于 2014-06-13T23:51:29.183 回答