我试着生成一个10阶多项式的值,它有11个系数。我也在尝试生成它的派生函数。我已经写了三个函数,如下所示。此代码生成polynomial.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;
}多项式的代码是inefficient.if,我想生成一个100次的多项式,这是不可能的。有没有一种方法可以生成多项式及其导数,可能是递归的,以避免繁琐的代码。
发布于 2011-03-23 01:44:49
一种解决方案是接受系数数组及其长度:
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);发布于 2011-03-23 01:45:53
您可以重写函数以获取x值,一个系数数组,然后是长度。
https://stackoverflow.com/questions/5395533
复制相似问题