[英]R: Problem with MonteCarlo Simulation and Normal Distribution
I am trying to solve the following exercise:我正在尝试解决以下练习:
Let Z_n be maximum of n standard normal observations.令 Z_n 为 n 个标准正态观测值的最大值。 Estimate what n should be so that P(Z_n>4)=0.25估计 n 应该是多少,使得 P(Z_n>4)=0.25
I have tried following code and I know the answer is about n=9000 because it returns aproximately 0.25.我尝试了以下代码,我知道答案大约是 n=9000,因为它返回大约 0.25。 I should change my code so that n is the output and not the input.我应该更改我的代码,以便 n 是 output 而不是输入。
n=9000
x1 <- sapply(1:n, function(i){max(rnorm(n=n,0,1))})
length(x1[x1>4])/length(x1)
How can I do that?我怎样才能做到这一点?
Thanks for helping!感谢您的帮助!
Well, you could select appropriate range and then just do binary search.好吧,你可以 select 适当的范围,然后只做二进制搜索。 Just remember, result will depend on number of samples and RNG seed.请记住,结果将取决于样本数量和 RNG 种子。
Zn <- function(n) {
max(rnorm(n))
}
Sample <- function(N, n) {
set.seed(312345) # sample same sequence of numbers
x <- replicate(N, Zn(n))
sum( x > 4.0 )/N
}
P <- 0.25
BinarySearch <- function(n_start, n_end, N) {
lo <- n_start
hi <- n_end
s_lo <- Sample(N, lo)
s_hi <- Sample(N, hi)
if (s_lo > P)
return(list(-1, 0.0, 0.0)) # wrong low end of interval
if (s_hi < P)
return(list(-2, 0.0, 0.0)) # wrong high end of interval
while (hi-lo > 1) {
me <- (hi+lo) %/% 2
s_me <- Sample(N, me)
if (s_me >= P)
hi <- me
else
lo <- me
cat("hi = ", hi, "lo = ", lo, "S = ", s_me, "\n")
}
list(hi, Sample(N, hi-1), Sample(N, hi))
}
q <- BinarySearch(9000, 10000, 100000) # range [9000...10000] with 100K points sampled
print(q[1]) # n at which we have P(Zn(n)>4)>=0.25
print(q[2]) # P(Zn(n-1)>4)
print(q[3]) # P(Zn(n)>4)
As a result, I've got结果,我得到了
9089
0.24984
0.25015
which looks reasonable.这看起来很合理。 It is quite slow though...虽然速度很慢...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.