生成10阶多项式的值及其在C中的导数

Was*_*uel 1 c polynomial-math

我试图生成具有11个系数的10阶多项式的值.我也试图产生它的衍生物.我写了三个函数如下所示.此代码生成多项式的值.a1到a10是系数.

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)+a4*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;
             }
Run Code Online (Sandbox Code Playgroud)

此代码生成它调用函数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;
           }
Run Code Online (Sandbox Code Playgroud)

多项式的代码是低效的.如果我想生成一个100阶多项式,它将变得不可能.有没有办法可以递归生成多项式及其导数,以避免笨重的代码.

nmi*_*els 6

一种解决方案是接受一系列系数及其长度:

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;
}
Run Code Online (Sandbox Code Playgroud)

递归解决方案很漂亮,但这不是Lisp.无论如何,类似的方法可以用于衍生物.请记住,在C中,函数的数组参数变为指针,所以你不能使用酷的东西sizeof来获取它们的长度.

编辑:响应注释,您可以在coefficients构造数组时强制执行您的要求.或者,如果您不负责该代码,您可以将其粘贴在函数中(如此)(如此:hackishly):

if (coefficients[0] == 0 || coefficients[1] == 0 || coefficients[order-1] == 0)
    assert(0);
Run Code Online (Sandbox Code Playgroud)