所以,我已经编写了这段代码,可以有效地估计定义为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)