Was*_*uel 0 c polynomial-math numerical-methods
我在c中创建了一个程序,该程序假设要使用牛顿拉夫森方法估算10阶多项式的根。用户输入10个系数,并假设估计方程的根。绝对相对误差为0.00000001,允许的最大迭代次数为70。示例代码如下。
n=0;
while(abserr<=0.00000001){
yold=y;
y = y-(poly(y,coefficients,11)/poly_der(y,coefficients,11));
ynew = y;
error=ynew-yold;
abserr=sqrt(error*error);
printf("iteration x%d = %.2f error =%.2f\n",n+1,y,abserr);
n++;
iteration++;
if(iteration==70){
printf("you have reached the maximum number of iterations\n");
break;}
}
Run Code Online (Sandbox Code Playgroud)
函数poly和poly_der分别计算多项式的值及其导数。下面有定义。
float poly(float x, float coefficients[], int order)
{
int idx;
float total;
for (idx = 0; idx < order; idx++)
total += coefficients[idx] * pow(x, idx);
return total;
}
float poly_der(float x, float coefficients[], int order)
{
int idx;
float total;
for (idx = 0; idx < order; idx++)
total += coefficients[idx] * deri(x, idx);
return total;
}
Run Code Online (Sandbox Code Playgroud)
deri是用于计算多项式中项的导数的函数。不幸的是,该程序产生了意外的结果。我无法弄清楚哪里出错了,因为它可以编译并运行良好。还有另一种方法可以使用牛顿法估算根。我如何改善程序,使其产生所需的结果。
您有几个单位化变量:(total两次),貌似iteration也是如此。如果不初始化变量,则其值是不确定的,并且在同一程序的运行之间甚至可能有所不同。
不要total = 0.在进入循环前poly和poly_der。