Your code has a few problems in it, the first one being that your code may infinitely loop as you try to have an infinite accuracy for a (possibly) irrational number. Although doubles do not have an infinite accuracy, I certainly wouldn't recommend trying to evaluate that function to that high of a degree of accuracy. The solution to this is to add some sort of 'precision' or 'epsilon' value (as mentioned in the comments below). Or even better to break out of the loop when increment
becomes too small (as @Pete Becker suggested):
double _sqrt(const double& n)
{
const double precision = 0.000001;
double increment = 1.0, sqrt = 0.0;
while (true)
{
if (increment <= precision)
break;
else if (sqrt * sqrt > n)
{
sqrt -= increment;
increment *= 0.1;
}
else
sqrt += increment;
}
return sqrt;
}
You can of course do this with the standard library, using std::sqrt
, but I assume you are doing this for fun.
If you are interested in other square root algorithms, there are some scary looking ones on Wikipedia here.
One that I personally like is Newton's Method, but this is for finding the root's of functions in general.
An application of this for the square root function that I copied and modified from here is:
double _sqrt(const double& n)
{
const double precision = 0.00001;
double sqrt, x = n;
while (true)
{
sqrt = 0.5 * (x + (n / x));
if (std::abs(sqrt - x) < precision)
break;
x = sqrt;
}
return sqrt;
}