Click to See Complete Forum and Search --> : Polynomials


upe
January 23rd, 2002, 09:07 PM
Ok this is the problem, I have the rest of the program done, but I need a function that evaluates a polynomial. Say it is 5x^3+2x^2+X+3
Index and power : 3 2 1 0
The array: coefcients |5||2||1||3|

I need to be able to plug 4 into this and get an answer back. I am have been tryin it for a long *** time, anybody have a way to do it? Thanks

upe
January 23rd, 2002, 09:07 PM
Ok this is the problem, I have the rest of the program done, but I need a function that evaluates a polynomial. Say it is 5x^3+2x^2+X+3
Index and power : 3 2 1 0
The array: coefcients |5||2||1||3|

I need to be able to plug 4 into this and get an answer back. I am have been tryin it for a long *** time, anybody have a way to do it? Thanks

Sammy D'Souza
January 23rd, 2002, 09:39 PM
I can give you some theory here and also a basic inkling... see if it helps... OK?

the expression anxn + an-1xn-1 + …. A1x1 + a0x0
can be evaluated as

x(x(x(… x(an) + an-1) + … ) + a0

for example,
5x3 + 2x2 + x + 3
really is
x(x(x( 5 ) + 2 ) + 1 ) + 3

so all u wld need wld be the array of coefficients and the power of the expression

i.e., given {5, 2, 1, 3} and the value of x to be evaluated at, say 4

u cld write something like

int n = sizeof(a ) / sizeof(a[0])
double d = 0.0;

for (int k = 0, k < n - 1, k++)
{
d += a[k]
d *= x;
}
d += a[n-1];

or something similar…. U may want to verify the boundary condtions.

Hope this helps

-sammy

NMTop40
January 24th, 2002, 06:04 AM
In this example order is the order of the polynomial. The size of the array coeffs is order+1


double poly( double *coeffs, int order, double x )
{
assert ( order > 0 );
double result = coeffs[ order ];
while ( order-- )
{
result *= x;
result += coeffs[order];
}
return result;
}





The best things come to those who rate