Square root function As a programming exercise I made a square root function in C# using recursion, here is the function:

static double root(double x, double increment, double num)
{
    num += increment;
    if ((num * num).ToString() == x.ToString())
        return num;
    else if (num * num &lt; x)
        return root(x, Math.Abs(increment), num);
    else if (num * num &gt; x)
        return root(x, Math.Abs(increment / 2) * -1, num);
    else
        return double.NaN;
}

static double sqroot(double x)
{
    return root(x, 10, 0);
}


It is able to do int.MaxValue without a problem, but my question is, how can this be improved?
A couple of things. 

Is the string conversions really necessary just for comparing 2 doubles?

Figuring the squared value on the fly seems to lead to a bit of repetition

Also, optional parameters make the initial calling simpler.

static double root(double x, double increment = 10, double num = 0)
{
    num += increment;
    double sqrdValue = num * num;
    if (sqrdValue == x)
        return num;
    else if (sqrdValue &lt; x)
        return root(x, Math.Abs(increment), num);
    else if (sqrdValue &gt; x)
        return root(x, Math.Abs(increment / 2) * -1, num);
    else
        return double.NaN;
}


Since it appears that integers will introduce rounding errors, you filter for that by checking if the difference is less than or equal to 0.000000000000001, instead of just equal to, which gives the same degree of accuracy in the final answer as the built-in sqrt method of the Math class.

static double root(double x, double increment = 10, double num = 0)
{
    double maxError = 0.000000000000001;
    num += increment;
    double sqrdValue = num * num;
    if (Math.Abs(sqrdValue - x) &lt;= maxError)
        return num;
    else if (sqrdValue &lt; x)
        return root(x, Math.Abs(increment), num);
    else if (sqrdValue &gt; x)
        return root(x, Math.Abs(increment / 2) * -1, num);
    else
        return double.NaN;
}