I am trying to compute the coverage probability for an unspecified distribution. I have copied my r
codes below and the corresponding error message.
Firstly, I defined the CDF as below.
CD_theta <- function(x, p, n) {
1 - pbinom (x, size = n, prob = p) + 1/2 * dbinom(x, size = n, prob = p)
Then used the following command to estimate the coverage probability.
N <- 10000
n <- 10
p <- 0.5
set.seed(1)
x <- rbinom(N, prob=p, size=n)
covered <- numeric()
cilower <- numeric()
ciupper <- numeric()
for (i in 1:N) {
CD_theta <- function(x, p, n) {
1 - pbinom (x, size = n, prob = p) + 1/2 * dbinom(x, size = n, prob = p)
}
cilower <- uniroot(function(p) CD_theta(x[i], p, n) - 0.025, c(0, 1))$root
ciupper <- uniroot(function(p) CD_theta(x[i], p, n) - 0.975, c(0, 1))$root
covered[i] <- (cilower < p) & (p < ciupper)
}
mean(covered)
Error message and the output are below.
Error in uniroot(function(p) CD_theta(x[i], p, n) - 0.975, c(0, 1)) : f() values at end points not of opposite sign
mean(covered) [1] 0.9820282
Am I doing any mistake in coding? How can I prevent this?