user2458552
user2458552

Reputation: 419

While loop in R

I am stuck with a problem in simulation. I have to find the rate of convergence of a certain statistic. But I am unable to get the program to run. In fact, whenever I am running it, R hangs.

n=100
eps=0.001
del=0.001
T=3.24
z=abs((T-3.14159)/T)
while((z*(n^del))>eps)
{
    del=del+0.001
}
del

Upvotes: 1

Views: 1020

Answers (1)

Thomas
Thomas

Reputation: 44527

You've constructed for yourself an "infinite loop," which can happen quite easily when using either while or repeat statements. See R Language Definition.

A while loop expects a condition that goes from being TRUE to FALSE at some iteration, for example:

> a <- 1
> while(a < 5) a <- a + 1
> a
[1] 5

This will increment the a value by one on each loop iteration and then stop the loop when a==5.

Looking at your loop:

while((z*(n^del))>eps)
{
    del=del+0.001
}

You increment the del value, but your logical statement (z*(n^del))>eps is TRUE from the very beginning of the code and remains TRUE forever because the lefthand side of the inequality is always increasing, thus the infinite loop.

Upvotes: 2

Related Questions