参考资料:
Q:求方程:2*x*x*x-4*x*x+3*x-6=0的根,分别运用两种方法来实现,前提是我们已经知道这个方程只有一个根,否则的话下面的算法是无效的:
牛顿迭代法:
#include
#include
#include
float f(float x)
...{
return 2*x*x*x-4*x*x+3*x-6;
}
float fd(float x)
...{
return 6*x*x-8*x+3;
}
int main(void)
...{
float x0=1.5,x=1.5;
do...{
x0=x;
x=x0-f(x0)/fd(x0);//迭代公式求近似根;
}while(fabs(x-x0)>1e-4);
printf("the asymtomatic root is %f ",x0);
getch();
return 0;
}
/**//*2.000005*/二分法:
#include
#include
#include
float f(float x)
...{
return 2*x*x*x-4*x*x+3*x-6;
}
int main(void)
...{
float l=-10,r=10,root,mid;
while(fabs(l-r)>1e-4)...{
mid=(l+r)/2;
if(!f(mid))...{
root=mid;
break;
}if(f(l)*f(mid)<0)
r=mid;
else
l=mid;
}
root=mid;
printf("the only one root is %f ",root);
getch();
return 0;
}
/**//*2.000046*/我们可以比较二者的结果可以发现在同样的而且是较小的限制条件下牛顿迭代法要比二分法求的值的精确,但是如果把限制条件扩大的话,结果都是2,恰巧2就是这个方程的精确根了。