c语言/c++实现牛顿迭代法求解一元二次方程的两个根

下面是一段c语言代码听过牛顿迭代法可以求解一元二次方程的两个根,当然里面的参数还是很有讲究的,可以通过调节limit_min修改得到结果的精度,另外 a,b,c则代表方程为 ax2+bx+c=0ax^2+bx+c=0ax2+bx+c=0.好的,就说那么多,有问题的可以在下面留言哈。


float  newdun(float a, float b,float c,float x,float limit_min){
     float gradient=2*x*a+b;
     float y_value=x*x*a+b*x+c;
     float x_next= x-(y_value/gradient);
     if(fabs(x-x_next)<limit_min){
         return x_next;
     }
     else{
         return newdun(a,b,c,x_next,limit_min);
     }


}
int main()
{
  
    float a=1,b=4,c=3;
    float x_value1=newdun(a,b,c,100,0.1);
     float x_value2=newdun(a,b,c,-100,0.1);
    float x=x_value1;
    cout<<"the predict is :"<<x<<endl;
    cout<<"the y of predict is :"<<x*x*a+b*x+c<<endl;
    x=x_value2;
    cout<<"the predict is :"<<x<<endl;
    cout<<"the y of predict is :"<<x*x*a+b*x+c<<endl;
    return 0;
}

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐