// implementing square-root without calling any other functions // #include #include double mysqrt( double a) { double x = a/2; // initial estimate of square root int count; // loop counter for( count = 0; count < 5; ++count) // concise while loop { x = (x + a/x)/2; // Newton says this will improve the estimate printf( "x = %.18g\n", x); // debug } return x; } int main( void) { double a = 2; scanf( "%lf", &a); double x = mysqrt(a); double y = sqrt(a); printf( "a = %.18g\n", a); printf( "x = %.18g\n", x); printf( "y = %.18g\n", y); printf( "d = %.18g\n", x - y); return 0; } /* sample runs: x = 1.5 x = 1.41666666666666652 x = 1.41421568627450966 x = 1.41421356237468987 x = 1.41421356237309492 a = 2 x = 1.41421356237309492 y = 1.41421356237309515 d = -2.22044604925031308e-16 x = 2.25 x = 2.23611111111111116 x = 2.2360679779158037 x = 2.23606797749978981 x = 2.23606797749978981 a = 5 x = 2.23606797749978981 y = 2.23606797749978981 d = 0 x = 251 x = 127.492031872509955 x = 67.6678296579155756 x = 41.2229503947159017 x = 32.7406409948669932 a = 1000 x = 32.7406409948669932 y = 31.6227766016837926 d = 1.11786439318320063 */