Search code examples
c++sqrt

Why isn't this C funtion calculating sqrt working for decimals?


#include <iostream>

float calculating_root(float N, float root_N, float increment)
{
    int safety=1;
    while(safety==1)
    {
        if (N == (root_N*root_N))
        {
            safety=0;
            return root_N;  
        }
        else if(N<((root_N+increment)*(root_N+increment)))
        {
            safety=0;
            return calculating_root(N,root_N, increment*0.1);
        }
        root_N=root_N+increment;
    }
}

int main()
{
    float N, root_N=0.0, increment=1000.0;

    scanf("%f",&N);

    float x = calculating_root(N, root_N, increment);

    printf("\n%g\n",x);

    return 0;
}

I've been thinking about it for such a long time. I guess I don't have other ideas, everything seems perfect? Does anyone sees a mistake?


Solution

  • Using == for comparing floating point numbers that you calculated is not advised. Especially in this case N might actually be a number that is not representable by any float a such that a*a == N.

    so instead of

    N == (root_N*root_N)
    

    try to use something like

    fabs(N-(root_N*root_N)) < epsilon
    

    Where epsilon is your acceptable rounding error. You could choose something like const float epsilon = 0.000001f. I think in this case you might need something above the machine epsilon, because you're potentially accumulating the error.

    You could also improve precision somewhat by using double instead of float. That will however not replace the need for the epsilon, only allow you to choose a lower epsilon.