开发者

generating the value of a 10 order polynomial and its derivative in C

开发者 https://www.devze.com 2023-02-18 06:19 出处:网络
Am trying to generate the value of a 10 order polynomial with 11 coefficients. Am also trying to generate its derivative. i have written a three functions shown below.

Am trying to generate the value of a 10 order polynomial with 11 coefficients. Am also trying to generate its derivative. i have written a three functions shown below. this code generates the value of the polynomial.a1 upto a10 are the coefficients.

float polynm( float a0,float a1,float a2,float a3,float a4,float a5,float a6,float a7,float a8,float a9,float a10,float x)
     {
          float poly = a0 + a1*x + a2*pow(x,2)+a3*pow(x,3)+a开发者_开发技巧4*pow(x,4)+a5*pow(x,5)+a6*pow(x,6)+a7*pow(x,7)+a8*pow(x,8)+a9*pow(x,9)+a10*pow(x,10);
             return poly;
             }

this code generates the value of the derivative of the polynomial it calls a function deri

 float polynm_der(float a0,float a1,float a2,float a3,float a4,float a5,float a6,float a7,float a8,float a9,float a10,float x)
    {  float der = a1 + a2*deri(x,2)+a3*deri(x,3)+a4*deri(x,4)+a5*deri(x,5)+a6*deri(x,6)+a7*deri(x,7)+a8*deri(x,8)+a9*deri(x,9)+a10*deri(x,10);
       return der;
       }
deri is below
float deri(float x,int n)
   {   
         float term_der = n*pow(x,n-1);
           return term_der;
           }

the code for the polynomial is inefficient.if i wanted to generate an 100 order polynomial it would become impossible. is there a way i can generate the polynomial and its derivative maybe recursively to avoid the unwieldy code.


One solution is to accept an array of coefficients and its length:

float poly(int x, float coefficients[], int order)
{
    int idx;
    float total;

    for (idx = 0; idx < order; idx++)
        total += coefficients[idx] * pow(x, idx);
    return total;
}

The recursive solution would be beautiful, but this isn't Lisp. Anyway, a similar approach can be used for derivatives. Just keep in mind the fact that in C, array parameters to functions turn into pointers, so you can't use cool things like sizeof to get their lengths.

Edit: In response to the comment, you can enforce your requirements when the coefficients array is constructed. Alternatively, if you're not in charge of that code, you can stick it in the function (hackishly) like so:

if (coefficients[0] == 0 || coefficients[1] == 0 || coefficients[order-1] == 0)
    assert(0);


You could rewrite the functions to take the x value, an array of coefficients, and then the length.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号