Horner's rule in C++
While trying to evaulate polynomials using Horner's Rule I have a sample code segment like so:
int Horner( int a[], int n, int x )
{
int result = a[n];
for(int i=开发者_StackOverflow社区n-1; i >= 0 ; --i)
result = result * x + a[i];
return result;
}
I understand that a
is an array of coefficients and that x
is the value that I would like to evaluate at. My question is what is the n
for?
n is the degree of the polynome (and a polynome of degree n, aside from 0 which is kind of special, has n+1 coefficients, so size of array = n+1, n = size of array - 1)
n is the size of the array
'n' is index of the last element in the array. Therefore, n is one less than the size of the array.
The code appears to be incorrect. The statement:
int result = a[n];
should fail if n is size of the array... If n is the size of the array minus 1, then it will work but the contract of the function is very strange in this case. It is impossible to pass empty array to the function, which is not generic and requires additional checking on caller's side.
In C++, the language does not provide native support for getting the length of an array. Because of that, code must often maintain a separate variable that holds the length. In this example, the n parameter tells the Horner function how many elements are in the array.
In C++ it's idiomatic to pass the number of elements. Since arrays are 0 based, the last element of the array is arr[n-1]
.
精彩评论