gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:55:10 25 4
gpt4 key购买 nike

我正在尝试生成具有 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 阶多项式,那将变得不可能。有没有一种方法可以递归地生成多项式及其导数以避免笨拙的代码。

最佳答案

一个解决方案是接受一个系数数组及其长度:

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 数组时强制执行您的要求。或者,如果您不负责该代码,则可以像这样(笨拙地)将其粘贴到函数中:

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

关于c - 在 C 中生成 10 阶多项式及其导数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5395533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com