Hi! Friends, Whatzz up? I haven't got something special for you today. But it is a problem that you must have encountered in your High School, then why not write code for it? So lets get started!
given the coefficients a0,a1,…,an and a value for x :
Horner’s method can be used to evaluate polynomial in O(n) time. To understand the method, let us consider
3x^3 - 5x^2 + 4x - 8. The polynomial can be evaluated as ((3x – 5)x + 4)x – 8. The idea is to initialize result as coefficient of x^n which is 3 in this case, repeatedly multiply result with x and add next coefficient to result. Finally return result.
Following is the C++ implementation of Horner''s Rule:
#include <iostream>
using namespace std;
int horner(int a[], int n, int x)
{
int y = a[0];
for (int i=1; i<n; i++)
y = y*x + a[i];
return y;
}
int main()
{
// Evaluating value of 3x3 - 5x2 + 4x - 8 for x = 3
int a[] = {3, -5, 4, -8};
int x = 3;
int n = sizeof(a)/sizeof(a[0]);
cout << "Value of polynomial is eual to " << horner(a, n, x);
return 0;
}
No comments:
Post a Comment