Why this for loop is infinite?

Viewed 259

I have such for loop and when step is (0;1) it becomes infinite. If step is [1;..) it works well.

  public interface FindMinI {
    double function(double x);

    static double findMinOfFuncOnInterval(int begin, int end, double step, FindMinI func)
    {
        double min = Double.MAX_VALUE;

        for (int i = begin; i <= end ; i += step) {

            if(func.function(i) <= min)
                min = func.function(i);

        }
        return min;
    }
 }
5 Answers

If you try with step between (0,1) this will be casted to int when adding to i, as a result you will add 0 to i in every iteration which will lead to infinite loop!

It will be infinite, because if step is 0 then adding zero to i would do nothing. No incrementation means infinite loop.

If step is 0 you're adding 0 to i meaning there's nothing being added to the value, and it gets stuck as infinite.

Since you supply step as a double, having values like 0.0001 is possible. However, since i is an integer the conversion is made from double to int, and 0.0001 -> 0. When you cast a value that's less than 1 and more than 0 as an integer, it becomes 0.

Change i to double and you can use decimal values to increment.

Alternatively, you could change step to int, but you wouldn't be able to use decimal steps in that case

A similar situation can be found with division or multiplication to demonstrate the double example:

(int) (500 * 0.0001) -> 0.05 as an integer = 0

So when you add a double step with a decimal value (exclusively a decimal value) to an integer, step becomes 0, 0 is added to i and it becomes infinite.

When it is (0,1) always its a satisfying condition, the loop never ends.

When it is (0,1), inside for loop you are verifying i <= end, this is all time passing condition. So, your loop won't break.

Related