Bogdan Klinowitzki
Bogdan Klinowitzki

Reputation: 23

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

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];
  }

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


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.

Upvotes: 0

Views: 79

Answers (1)

queeg
queeg

Reputation: 9473

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.

Upvotes: 2

Related Questions