[英]Making a more efficient monte carlo simulation
So, I've written this code that should effectively estimate the area under the curve of the function defined as h(x). 所以,我编写了这个代码,它应该有效地估计定义为h(x)的函数曲线下的面积。 My problem is that i need to be able to estimate the area to within 6 decimal places, but the algorithm i've defined in estimateN seems to be using too heavy for my machine. 我的问题是我需要能够将区域估计到小数点后6位,但我在estimateN中定义的算法似乎对我的机器来说太重了。 Essentially the question is how can i make the following code more efficient? 基本上问题是如何使以下代码更有效? Is there a way i can get rid of that loop? 有没有办法摆脱那个循环?
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)
Replace this code: 替换此代码:
count = 0
k = 1
while(k <= n){
if(ypoints[k]<=h(xpoints[k]))
count = count+1
k = k+1
}
With this line: 有了这条线:
count <- sum(ypoints <= h(xpoints))
If it's truly efficiency you're striving for, integrate
is several orders of magnitude faster (not to mention more memory efficient) for this problem. 如果你真正想要的是效率,那么对于这个问题, 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.