Horner’s Rule158 views

AlgoPill
 function hornersRule(coeff, c) {
    var result = 0,
        i = 0;
    for (i = coeff.length - 1; i >= 0; i--) {
        result = coeff[i] + result * c;
    }
    return result;
}

Problem Statement: Find the value of a given polynomial P(x) = a0 + a1x + a2x2 + a3x3… an-1xn-1 for a given value of x

Solution: Horner’s rule can be used to solve this problem in O(n) time where n is the maximum power of variable x in the polynomial.

this method works by evaluating the polynomial in a different form which requires reduced number of operations.

P(x) = a0 + a1x + a2x2 + a3x3… an-1xn-1

P(x) = a0 + x(a1 + x(a2 + x(a3+… +(an-2+ xan-1)  … )))

The input to this algorithm is an array of co-efficient  in the polynomial, i.e. coeff[i] = ai, and a number c which is the given value of x at which we have to calculate P(x)

The algorithm maintains a loop invariant which we state below.

Loop Invariant: at the start of the loop the variable result contains a partially calculated polynomial Qi(x)

Qi(x) = ai+1 + ai+2x + ai+3x2 ….. an-1xn-2-i

Intialization: i=n-1

Qn-1(x) = 0

Maintenance:

Qn-2(x) = an-1

Qn-3(x) = an-2 + x*an-1

Qi (x) = ai+1 + ai+2x + ai+3x2 + …. an-1xn-2-i

Qi-1(x) = ai + x*Qi(x)

= ai + ai+1x + ai+2x2 + ai+3x3 + … an-1xn-1-i

= Qi-1(x)

Termination:

Q-1(x) = a0 + a1x + a2x2 + …. an-1xn-2 +1

Q-1 (x) = a0 + a1x + a2x2 + …. an-1xn-1

which is equivalent to P(c) if we substitute  c for x.

Thus this algorithm correctly calculates

Post a Comment

You must be logged in to post a comment.