问题
I am trying to solve the following exercise:
Let Z_n be maximum of n standard normal observations. Estimate what n should be so that 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. I should change my code so that n is the output and not the input.
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!
回答1:
Well, you could select appropriate range and then just do binary search. Just remember, result will depend on number of samples and RNG seed.
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...
来源:https://stackoverflow.com/questions/61290213/r-problem-with-montecarlo-simulation-and-normal-distribution