Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will this algorithm terminate?

With different values in a collection, will this algorithm (pseudeocode) ever terminate?

while (curElement != average(allElements))
{
    curElement = average(allElements);
    nextElement();
}

Note that I'm assuming that we will re-start from the beginning if we're at the end of the array.

like image 903
Franz Avatar asked Apr 29 '26 13:04

Franz


1 Answers

Since this is pseudocode, a simple example with 2 elements will reveal that there are cases where the program won't terminate:

x = 0, y = 1;

          x     y
Step 1:   0.5   1
Step 2:   0.5   0.75
Step 3:   0.635 0.75
//and so one

With some math involved, lim(x-y) = lim( 1 / 2^n )

So the numbers converge, but they're never equal.

However, if you'd actually implement this on a computer, they will turn out equal because of hardware limitations - not all numbers can be expressed in a limited number of bits.

like image 75
Luchian Grigore Avatar answered May 02 '26 04:05

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!