Polynomial Evaluation Algorithm in C++


// P(x) = (Cn * x^n )+ (Cn-1 * x^(n-1)) + .... (C0 * x ^ 0) template<typename T> T PolyEval(T coeff[], int n, const T& x){ T y=1, value = coeff[0]; for(int i=0;i<n; ++i){ y*=x; value +=y*coeff[i]; } return value }



//Horner rule for poly eval //P(x)= (.. (Cn * x + Cn-1) *x + Cn-2) * x + ...) * x + C0 template<typename T> T HornerPolyEval(T coeff[], int n, const T& x){ T value=coeff[n]; for(int i=1; i<=n; ++i){ value= value*x + coeff[n-i]; } return value }

No comments:

Post a Comment

would you like it. :)