/// G. Hagopian -- Implementing the Babylonian algorithm

#include "std_lib_facilities.h"

bool debug = true;

double baby(double);
///double abs(double x) { return (x>=0) ? x : -x; }

int main()
try {
    double x;
    cout << "\nEnter a double for it's square root: ";
    while(cin >> x) {
        cout << baby(x);
        cout << "\nEnter a double for it's square root: ";
    }
    if(!cin) ///error("That was a bad entry!");
         throw runtime_error("Bad entry!");
}
catch (exception& e) {
    cerr << "error: " << e.what() << '\n';
    return 1;
}
catch (...) {
    cerr << "Oops: unknown exception!\n";
    return 2;
}

double baby(double A) {
    if(A<0) {
        error("\nCan't compute the square root of a negative.");
    }
    double tolerance = A*5.e-18;  ///note: relative?
    double x = A;
    double next = A/2;
    while(abs(x-next)>tolerance) {
        if(debug) cout << "\nnext = " <<
            setprecision(18) << next;
        x = next;
        next = (A/x + x)/2;
    }
    cout << endl;
    return next;
}
