尝试生成具有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;
}
此代码生成它调用函数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;
}
多项式的代码是低效的。如果我想生成100阶多项式,那将变得不可能。有没有办法可以递归生成多项式及其导数,以避免笨重的代码。
答案 0 :(得分: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;
}
递归解决方案很漂亮,但这不是Lisp。无论如何,类似的方法可以用于衍生物。请记住,在C中,函数的数组参数变为指针,所以你不能使用像sizeof
这样的酷函数来获取它们的长度。
编辑:在回复评论时,您可以在构建coefficients
数组时强制执行您的要求。或者,如果您不负责该代码,您可以像这样坚持功能(hackishly):
if (coefficients[0] == 0 || coefficients[1] == 0 || coefficients[order-1] == 0)
assert(0);
答案 1 :(得分:0)
您可以重写函数以获取x值,系数数组,然后是长度。