Of course this code is written in C++, which is my favorite programming language. I love programming in this language:))
But back to the main topic 😃
Horner's scheme has two applications
-
we use it to divide polynomials by a polynomial, but only of the first degree.
-
to calculate the value of polynomials for a given argument.
We will deal with the second case. We have the following polynomial:
in the first case we have
and second case we have:
For a third degree polynomial we will have (take my word
for it) six multiplications and three additions.
When the degree of the polynomial increases, the number of multiplications increases.
We all know that computers perform multiplication much slower than addition.
--
And here comes the time for Horner's algorithm (or Horner's scheme). To use it, we need to simplify the polynomial.
What is it about?
We have a polynomial like this:
If we exclude all the x's in front of the bracket, we get:
And we can represent this above record in the form of a loop:
And now the same in C/C++:
float f = a[4];
for(int i = 3; i >= 0; --i)
f = f * x + a[i];
And from there it's only one step to writing an iterative function that calculates
the value of the polynomial at a given point:
// iterative version
float hornerIter(Vector& a, int& n, float& x)
{
int i = 0;
float f = 0.0f;
f = a[0];
for(int i = 1; i <= n; ++i)
f = f * x + a[i];
return f;
}
Here's the recursive version:
// recursive version
float hornerRec(Vector& a, int n, float x)
{
if(n == 0)
return a[0];
return x * hornerRec(a, n - 1, x) + a[n];
}
license
MIT