Kho*_*eir 5 simulation statistics performance r
所以,我编写了这个代码,它应该有效地估计定义为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)
Run Code Online (Sandbox Code Playgroud)
替换此代码:
count = 0
k = 1
while(k <= n){
if(ypoints[k]<=h(xpoints[k]))
count = count+1
k = k+1
}
Run Code Online (Sandbox Code Playgroud)
有了这条线:
count <- sum(ypoints <= h(xpoints))
Run Code Online (Sandbox Code Playgroud)