sqrt2.cpp


      #include <stdio.h>
      
      double our_sqrt(double y)  // solve x*x=y correct to three decimal places
      { double min_x = 0;
        double max_x = y+1;
        double acceptable_accuracy = 0.0;
        while (max_x-min_x > acceptable_accuracy)
        { const double guess_x = (min_x+max_x)/2.0;
          const double guess_y = guess_x * guess_x;
          if (guess_y == y)
            return guess_x;
          else if (guess_y > y)
            max_x=guess_x;
          else
            min_x=guess_x;
          acceptable_accuracy=guess_x/1000.0; }
        return (min_x+max_x)/2.0; }
      
      void main(void)
      { printf("for reference\n");
        printf("  sqrt(2) really = %f\n", sqrt(2));
        printf("testing our function\n");
        printf("  sqrt(2) is about %f\n", our_sqrt(2));
        printf("  sqrt(200) is about %f\n", our_sqrt(200));
        printf("  sqrt(20000) is about %f\n", our_sqrt(200));
        printf("  sqrt(1000000) is about %f\n", our_sqrt(1000000)); 
        printf("  sqrt(2000000) is about %f\n", our_sqrt(2000000)); }