Home > Software design >  How do I count Iterations in loop and compare it to the iterations from the other class?
How do I count Iterations in loop and compare it to the iterations from the other class?

Time:11-07

I wrote code that solves polynomials in two ways:

  1. normal form a0x a1x...an*x
  2. Horner method.

Now, what I need, is to count the amount of multiplications in both classes and compare them. So, my program could decide in which case the Horner method is a better way to solve a polynomial. I couldn't find any ways to count the multiplicators myself.

  static int count_2=0;
  static int count_1=0;

//---------------------------------------------------------------------------//
  public static double evalSimple(double[] a, double x) {
    double y_temp = 0;
    double y=0;
    int n=1;
    for(int i=1; i < a.length ;   i) {
      y_temp = (a[i] * Math.pow(x,n));
      y = y   y_temp;
        n;
        count_1;
    }
    System.out.println(count_1);
    return y a[0];
  }

//---------------------------------------------------------------------------//
public static double evalHorner(double[] a, double x) {

  double y = 0;
  for (int i = a.length - 1; i >= 0; i--) {
    y = a[i]   y * x;
      count_2;
  }
  System.out.println(count_2);
  return y;
}
  //---------------------------------------------------------------------------//

//here would be the class to compare the amount of the multiplikations 


//---------------------------------------------------------------------------//
  public static void main(String[] args) {
    double[] b = {3,4,5};
    System.out.println(evalSimple(b, 3));
    System.out.println(evalHorner(b, 3));
  }
}

I tried to initiate the variables count_1 & count_2 and put them in the for-loop, but I didn't get how to return the value (not just to print them in console) of them for the test environment.

CodePudding user response:

A function can always return only one value. But you can make this a result object. I made the example with only one of your methods:

class Result {
    double solution;
    int iterations;
}

public static Result evalHorner(double[] a, double x) {
    Result result = new Result();

    for (int i = a.length - 1; i >= 0; i--) {
        result.solution = a[i]   result.solution * x;
          result.iterations;
    }
    return result;
}

Also note that I did not use a global counter variable, so the returned value is fresh for the exact invocation.

  •  Tags:  
  • java
  • Related