创建迭代程序来估计多项式的根
我正在用 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;}
}
函数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;
}
deri 是计算多项式中一项的导数的函数。 不幸的是,这个程序产生了意想不到的结果。我不知道哪里出了问题,因为它编译并运行良好。有没有另一种方法可以使用牛顿法估计根。我怎样才能改进程序,使其产生所需的结果。
Am creating a program in c which is suppose to estimate the root of a 10 order polynomial using newton raphson method. The user enters 10 coefficients and it is suppose to estimate the root of the equation. the absolute relative error is 0.00000001 and maximum number of iterations allowed are 70. sample code is below.
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;}
}
the functions poly and poly_der calculate the value of the polynomial and its derivative respectively. there defnitions are below.
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;
}
deri is function which calculates the derivative of a term in the polynomial.
Unfortunately this program produces unexpected results. i cant figure out where am wrong because it compiles and runs fine. Is there another way i can estimate the root using newton's method. How can i improve the program so it produces the required results.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有几个统一的变量:
total
(两次)和看似iteration
。如果不初始化变量,则其值是未定义的,甚至在同一程序的运行之间可能会有所不同。在进入
poly
和poly_der
循环之前执行total = 0.
。You have several unitialized variables:
total
(twice) and seeminglyiteration
as well. If you don't initialize a variable, its value is undefined and may even differ between runs of the same program.Do
total = 0.
before entering the loop inpoly
andpoly_der
.以下是一些可能有帮助的事情:
Here are some things that might help: