double my_poly(double a[], double x, int degree){
long int i;
double result = a[0];
double xpwr= 1/x;
for(i=1; i<degree;i+=2){
xpwr = x * x * xpwr;
result = result + ((a[i] + (a[i+1] * x)) * xpwr);
}
return result;
}
The code above yields correct values for small-sized arrays. But when I use an array with a size 1000 the result comes wrong. Please, can you help me?
Edit: I have examined as suggested;
double b[4] = {1,2,4,5};
printf("%f\n", poly(b,2,3));
printf("%f\n", my_poly(b,2,3));
Output:
61.000000
21.000000
According to the @Ian Abbott 's comment I have added this code block before the return statement, to satisfy both even and odd degrees:
for(; i<=degree;i++){
xpwr = x * x * xpwr;
result += a[i] * xpwr;
}
So the test outputs are consistent.
printf("%f\n", poly(a,2,999));
printf("%f\n", my_poly(a,2,999));
Yields:
61.000000
61.000000
Adding that code block before the return statement solved my problem.
for(; i<=degree;i++){
xpwr = x * x * xpwr;
result += a[i] * xpwr;
}