Search code examples
javamathpolynomials

Writing a polynomial in facorized form in Java


So I have an array of coefficients of complex numbers. So if c= a+ib, a coefficient would be stored as (a,b). My array is called Coeff[i]. I'd like to write a function which would accept a variable, say z, and evaluate the polynomial. But the thing is, I don't want to use Math.Pow function I'd like to evaluate the polynomial like this:

enter image description here

I have tried writing down polynomials of degree 1,2,3,4 and by this I noticed a pattern(i mean it's kind of obvious). But then I could not think of a way of writing it that way. If anyone could help that would be great.

Maybe I should set up a loop that would start from the highest index and sum up the polynomial from inwards?

I think I have to set up a loop with these, but I'm not sure how to exactly: enter image description here


Solution

  • What you are describing is called Hormer's Method for evaluating polynomials. You can evaluate by starting at the highest order term and then repeatedly multiply it by z and then add the next highest order term, rinse repeat. It looks something like this:

    Complex eval(Complex z, Complex coeff[]) {
      Complex eval = 0;
    
      for (int i = coeff.length-1; i > 0; i--) {
        eval += Complex.add(coeff[i], Complex.mul(eval, z));
      }
    
      return eval + coeff[0];
    }
    

    You would need to do some validation on the inputs (i.e. make sure the array isn't empty), and this assumes you have a class for manipulating complex numbers (I don't recall if there's a standard one available). Also, I haven't tested this, so take it with a grain of salt, but this is the general idea.