fork download
  1. /* [Exercise 5] Bisection method */
  2. #include <stdio.h>
  3. #include <math.h>
  4. #define MAX_N 10000000
  5. int main(void) {
  6. int n, k;
  7. float x1, x2, x3;
  8. for( n = 1; n <= MAX_N; n *= 10 ) {
  9. x1 = 0;
  10. x2 = 10;
  11. for ( k = 0; k < n; k++ ) {
  12. x3 = (x1 + x2)/2;
  13. if (x3*x3-2 == 0){
  14. printf("Find! (n=%d)", k);
  15. break;
  16. }else if((x3*x3-2)*(x2*x2-2)>0)
  17. x2 = x3;
  18. else
  19. x1 = x3;
  20. }
  21. printf( "n= %d, estimated= %.10f, error= %.3e\n", n, x3, x3-sqrt(2) );
  22. }
  23. return 0;
  24. }
  25.  
Success #stdin #stdout 0.1s 5316KB
stdin
Standard input is empty
stdout
n= 1, estimated= 5.0000000000, error= 3.586e+00
n= 10, estimated= 1.4160156250, error= 1.802e-03
n= 100, estimated= 1.4142136574, error= 9.501e-08
n= 1000, estimated= 1.4142136574, error= 9.501e-08
n= 10000, estimated= 1.4142136574, error= 9.501e-08
n= 100000, estimated= 1.4142136574, error= 9.501e-08
n= 1000000, estimated= 1.4142136574, error= 9.501e-08
n= 10000000, estimated= 1.4142136574, error= 9.501e-08