Polynomials without the power function

The quadratic (i.e. degree 2) polynomial

y = c1 x2 + c2 x + c3

can be rearranged as

y = (c1 x + c2) x + c3

The same pattern can be applied to a cubic (degree 3) polynomial

y = c1 x3 + c2 x2 + c3 x + c4

y = (c1 x2 + c2x + c3) x + c4

Factoring the quadratic term inside the parenthesis gives

y = ( (c1 x + c2) x + c3) x + c4

This pattern is called Horner's rule for evaluating a polynomial. For hand calculation of low degree, it makes sense to use direct computation of the polynomial in its standard form. To evaluate a polynomial in a computer program, Horner's rule makes more sense, especially if speed and accuracy are important and the degree of the polynomial is large.

Here is an code that uses Horner's rule to repeatedly evaluate the same polynomial. The correct value is 1070.8.

Download the source

//  File:  horner.pde
//
//  Demonstrate Horner's rule for evaluating a polynomial

void setup() {
  Serial.begin(9600);
}

// ----------------------------------------------------------------------------
void loop() {
  int   n=5;                                 //  n coefficients for degree n-1
  float a[5] = {1.0, 3.0, 2.1, 4.0, -1.7};   //  Coefficients of made-up polynomial
  float x, y;
  
  x = 5.0;
  y = horner(n,a,x);
  Serial.print(x,2);  Serial.print("  ");   Serial.println(y,2);
  
}

// ----------------------------------------------------------------------------
//  y = horner(n,c,x) evaluates a polynomial y = f(x) at x.  The polynomial has
//                    degree n-1.  The coefficients of the polynomial are stored
//                    in the 1-D array c, which has n elements.
//
//  NOTE:  The polynomial coefficients are multipliers of monomial terms of
//         decreasing order.  In other words, the polynomial is assumed to be
//         written in the form
//
//            y = c_1*x^n + c_2*x^(n-1) + ... + c_(n-2)*x + c_(n-1)
//
//  Also note that if there are n coefficients, the polynomial is of degree n-1
//  and the largest index in c is n-1

float horner(int n, float *c, float x) {
  
  float f;
  
  f = c[0];
  for ( int i=1; i<n; i++ ) {
    f = f*x + c[i];
  }
  return(f);
}