Pergunta

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;
}
Foi útil?

Solução

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.

Outras dicas

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;
    }

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top