求解一元三次方程近似解的几种算法(C语言)
生活随笔
收集整理的這篇文章主要介紹了
求解一元三次方程近似解的几种算法(C语言)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.弦截法求根
?
?弦截法C語言實現如下:
//求根函數 float f( float x ){float y;y = ((a * x + b) * x + c) * x + d;return (y); }//求解與x軸交點 float xpoint( float x1, float x2 ){float y;y = ( x1 * f(x2) - x2 * f(x1) ) / ( f(x2) - f(x1) );return (y); }/* [ x1, x2 ]為給定的求根區間 */ float root( float x1, float x2 ) {//需滿足f(x1)與f(x2)異號int i;float x, y, y1;float a,b,c,d;printf("input a,b,c,d:\r\n");scanf("%f,%f,%f,%f",&a,&b,&c,&d);y1 = f(x1);do{x = xpoint(x1, x2);//求解與x軸交點y = f( x );if( y * y1 > 0 ){x1 = x;y1 = y;} else {x2 = x;}} while( fabs(y) >= 1e-6);//計算精度printf( "the value is %.14f\r\n", x );return (x); }2.牛頓迭代法求根
??牛頓迭代法C語言實現如下:
/* a 三次系數 b 二次系數 c 一次系數 d 常系數 num 計算初值 */ float solute( float a, float b, float c, float d, float num){float x ,x0 ,f ,f1;x = num;do{x0 = x;f = (( a*x0 + b )*x0 + c )*x0 + d;f1 = ( 3*a*x0 + 2*b )*x0 + c;x = x0 - f / f1;cnt++;} while ( fabs( x - x0 ) > 1e-6 );printf( "the value is %.14f \r\n", x );return( x ); }3.二分法求根
?二分法C語言實現如下:
/* a 三次系數 b 二次系數 c 一次系數 d 常系數 */ void dichotomy( float a, float b, float c, float d ){float a,b,c,d;float x1,x2,x0,fx1,fx2,fx0;//需滿足f(x1)與f(x2)異號,且x1 < x2do{//輸入求根范圍printf("input x1,x2:\r\n");scanf("%f,%f",&x1, &x2);fx1 = ((a * x1 + b) * x1 + c) * x1 + d;fx2 = ((a * x2 + b) * x2 + c) * x2 + d;} while( fx1 * fx2 >= 0 );do{x0 = ( x1 + x2 ) / 2;fx0 = (( a * x0 + b) * x0 + c) * x0 + d;if( (fx0 * fx1) < 0 ){x2 = x0;fx2 = fx0;} else {x1 = x0;fx1 = fx0;}} while( fabs( fx0 ) >= 1e-6 );//求根精度printf( "the value is %.14f \r\n", x0 ); }總結
以上是生活随笔為你收集整理的求解一元三次方程近似解的几种算法(C语言)的全部內容,希望文章能夠幫你解決所遇到的問題。