0

Can anyone explain the mathematical correctness of the following code to find the square root of a positive number in C++ ?

#include <iostream>
#include <cmath>

using namespace std;

int main(){
    float a; cin>>a;
    cout<<"Answer by Math library\n"<<sqrt(a)<<"\n";

    //the following is the code for finding the square root of a positive double

    double g=a;

    while(abs(g*g-a)>1e-8){
        g= (g+(a/g))/2;
    }

    cout<<"Answer by this algorithm\n"<<g<<"\n";

    return 0;
}
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
  • It does seem like a problem suitable for https://math.stackexchange.com/ – AlexG May 12 '17 at 10:50
  • I'm voting to close this question as off-topic because this is primarily a mathematics question, which belongs on [the Mathematics SE](https://math.stackexchange.com/). – You May 12 '17 at 10:51
  • 1
    Note that this question, as is, probably isn't appropriate for [math.se] given the C++ code. The first step would be to convert that to a more language-agnostic form. – Bernhard Barker May 12 '17 at 10:55

1 Answers1

1

It's an approximate algorithm for computing the square root, called Babylonian method (derived from Newton's method):

enter image description here

and you can read about it's Convergence in Wikipedia.

gsamaras
  • 71,951
  • 46
  • 188
  • 305