Home > Software design >  While loop ends although condition is not fully achieved
While loop ends although condition is not fully achieved

Time:12-20

I am using the below code to find how many iterations it takes for the confidence interval to become approximately 25. However, when I run it it stops with interval lengths which do not fit the criteria. They are close, but not between 24.99 and 25.01.

counter <- 0
r <- 50
while((r-25)>0.01){
    counter <- counter   1
    a <- replicate(500,profit())
    CI_l <- mean(a) - (sd(a)/sqrt(500))*qnorm(0.975)
    CI_u <- mean(a)   (sd(a)/sqrt(500))*qnorm(0.975)
    r <- CI_u-CI_l
}
cat("It took ", counter, " tries to get to an interval of", r)

I am sure that there are also easier ways to do this but my main concern is whether R is doing something wrong or I am.

CodePudding user response:

When r is well below 25, then (r-25) is well below 0.01, therefore the while condition is false and it ends.

r <- 1
(r-25)
# [1] -24
(r-25) > 0.01
# [1] FALSE

Use abs(.),

abs(r-25) > 0.01
# [1] TRUE

leading to

while(abs(r-25) > 0.01){
  # ...
}

I applaud the use of tolerance in a test of inequality; often the first attempt is while (r != 25), but according to Why are these numbers not equal? and R FAQ 7.31 it may never occur (even if r is very close to 25).

  • Related