【发布时间】:2018-05-14 18:18:04
【问题描述】:
我正在尝试使用 Newton-Raphson 方法逼近多项式的根。我编写的代码如下所示:
#include <stdio.h>
#include <math.h>
int main (){
double c, nq, nnq, nnnq, v, h, q, o;
o=2;
c=-0.55;
nq=-0.04625;
nnq=-0.55;
nnnq=1;
while(fabs(c-v) > 0.000001)
{
nq=((2*(o-1)+1)*(c)*(nnq)-(o-1)*nnnq)/((o-1)+1);
q=(-o*c*nq+o*nnq)/(1-(c*c));
h=(c-(nq/q));
printf("The better root is %.15lf\n",h);
v=c;
c=h;
}
}
我知道没有必要编写变量 o、c、nq 等,因为我可以使用它们的确切值。这是一个更大问题的一部分,我需要这些变量,所以忽略它。
这个程序输出这个:
The better root is -0.578030303030303
The better root is -0.591696792857493
The better root is -0.598609887802599
The better root is -0.602171714355970
The better root is -0.604024260228500
The better root is -0.604992519745332
The better root is -0.605499890229896
The better root is -0.605766110042157
The better root is -0.605905895095070
The better root is -0.605979319651017
The better root is -0.606017894664121
The better root is -0.606038162857992
The better root is -0.606048812800124
The better root is -0.606054408979837
The better root is -0.606057349623975
The better root is -0.606058894866533
The better root is -0.606059706860161
相反,它应该收敛到点 -0.57735026918963。我知道 Newton-Raphson 肯定会收敛,所以错误应该在代码上。我还尝试使用 printf 定位问题,我认为问题出现在第二次迭代中。我认为程序无法正确计算 nq 但我不知道为什么。
【问题讨论】:
-
一个严重的问题(虽然不是主要问题)是
v未初始化。这让我相信你在编译时没有启用警告(或者可能只是忽略警告)? -
你能把你想计算的多项式也添加到问题中吗?
-
@PaulR True,在另一个程序中,我有 v=-20 来确保 while 循环开始。无论哪种方式,输出都是相同的。
-
@Afshin 是Legendre polynomial for n=2: (1/2)*(3*x^2-1)
-
你确定一阶导数是正确的吗?我觉得很有趣。
标签: c while-loop newtons-method