Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading