-2

So I have trouble coding a loop of a polynomial with a given x to find f(x) in java. To put it simply, for example, I have an array of f(x) = C[0]*x^n + C[1]*x^(n-1).......C[n]n, how would I code a loop to find f(x) with the user's input of x? Attached below is my incomplete function

static double poly(double[] C, double x){
            int n=C.length-1;
            int K;
            double sum=0.0;
            //loop is supposed to go here
            return sum;
}
user3312298
  • 31
  • 1
  • 2
  • 5

3 Answers3

0

You need to increment the variable sum by each term in the polynomial i.e.

Sum += C[i]×(x^(n-i)).

So loop from i= 0 to n with the above increment operation.

shree.pat18
  • 21,449
  • 3
  • 43
  • 63
0

try this :

 static double poly(double[] C, double x){
                int n=C.length-1;
                int K;
                double sum=0.0;
                /***********/
                int i=0;
                for (k=n ,k>0;k--)
                 {
                 sum= c[i]*pow(x,k)+ sum;
                 i++;
                 }
                return sum;
    }
Zied R.
  • 4,964
  • 2
  • 36
  • 67
0

You do this most efficiently using the Horner scheme.

C[n]+C[n-1]*x+...+C[0]*x^n 
= 
C[n]+x*(C[n-1]+x*(C[n-2]+...x*C[0]))

or as a loop

pol=C[0]
for k = 1 to n do
    pol *=x
    pol += C[k]
end for
return pol
Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51