二分法(计算方法)
2016-01-15 00:00
274 查看
![](http://static.oschina.net/uploads/img/201601/15103700_uiNW.gif)
![](http://static.oschina.net/uploads/img/201601/15103700_qdK2.gif)
简单
二分法
1 // 采用二分法求方程 f(x)=x3-x-1=0在区间[1,2]内的一个实根, 使误差不超过0.001。要求给定方程条件和误差范围。 2 #include " iostream " 3 #include " math.h " 4 using namespace std; 5 float fun( float x ) 6 { 7 float y; 8 y = x * x * x - x - 1 ; 9 return y; 10 } 11 int main() 12 { 13 14 float a = 1.0000 ,b = 2.0000 ,x,y2,y1,m,n; int k; 15 printf( " k a b x f(x)\n " ); 16 printf( " -----------------------------------------------------------\n " ); 17 18 if ( fun(a) * fun(b) > 0 ) return 0 ; 19 else 20 { 21 22 for ( k = 1 ; fun(a) * fun(b) <= 0 ,k < 12 ;k ++ ) 23 { 24 25 m = (b - a) / pow( 2 ,k + 1 ); 26 x = (a + b) / 2 ; 27 y2 = fun(x); 28 y1 = fun(a); 29 30 if (fabs(y2) < m) return 0 ; 31 if (y1 * y2 < 0 ) { b = x; } 32 else { a = x ; y1 = fun(x) ;} 33 n = (b - a) / pow( 2 ,k + 1 ); 34 if ((b - a) >= n) 35 if (k < 10 ) printf( " %d %.9lf %.9lf %.9lf %.9lf\n " ,k,a,b,x,fun(x)); 36 else printf( " %d %.9lf %.9lf %.9lf %.9lf\n " ,k,a,b,x,fun(x)); 37 38 } 39 40 } 41 42 43 } 44 45 46 47 48 49 50 51