Search code examples
rwhile-loopconvergence

How do I implement a while loop until convergence in R?


I want to code a while loop which iteratively fills values in a vector until its values converge. Here is a reproducible example :

vector <- c()
# initalize first and 2nd element
vector[1] <- 1
vector[2] <- 1 + exp(-2)

The ith element of the vector should be (1 + exp(-i)) and therefore this suite should converge, as n goes to infinity, difference between the (ith) and (i-th -1) element should goes to zero. Let epsilon an arbitrarily small value :

epsilon <- 10E-3

The while loop I coded is :

# Fill the vector until difference between the i-th element and the element before it becomes negligible : 
while (vector[i]-vector[i-1] > epsilon){
  vector[i+1] <- vector[i] + exp(-i)
}

Which fails to create the requested vector.


Solution

  • It looks like you're missing an initialization of the i object as well as a way to increment i:

    vector <- c()
    # initalize first and 2nd element
    vector[1] <- 1
    vector[2] <- 1 + exp(-2)
    
    epsilon <- 10E-3
    
    # initialize i
    i <- 2
    
    while (vector[i]-vector[i-1] > epsilon){
      
      vector[i+1] <- vector[i] + exp(-i)
      
      # increase i
      i <- i + 1
      
    }
    

    This example should terminate after i = 6