#include using namespace std; bool close(const double a, const double b) { return fabs(a - b) < 0.000001; } // The Newton-Raphson method, N is what you want the square root of, // and g is just a rough guess at what that square root might be. // and doesn't matter much how bad the guess is, this procedure // improves the first guess very quickly. double nr(const double N, const double g) { cout << g << " squared " << setprecision(15) << g * g << "\n"; if (close(N, g * g)) return g; else return nr(N, (g + N / g) / 2); } int main() { cout << "number: "; const double n = read_double(); // see the note below const double s = nr(n, combine_mant_exp(0.9, exponent(n) / 2)); cout << setprecision(16) << s << " squared is " << s * s << "\n"; } // the original version of this function call was: // const double s = nr(n, n / 2); // n / 2 is a really bad guess at sqrt(n) but it still works really // well. This next version stars with a really good initial guess // and gets to an accurate answer even faster. Do not be worried if // you don't see exactly how that expression works, that isn't the // point today and you'll learn about this sort of thing before // verl long