Blog

sqrt() Function

by Thomas Spycher on September 10, 2010

This is the way sqrt works… Why do i have to code this by my own?

const float EPSILON = 1e-6;
 
float working = val;
    float diff = 0;
    float keep = 0;
    float result = 0;
    int counter = 0;
 
    do {
        result = (keep + working) / 2;
        //std::cout << "("<<keep<<"+"<<working<<") / 2 = " << result << "\n";
        diff = (result * result)-val;
        std::cout << "[ " << counter << " ] " << working << "\n";
        if(diff <= 0) {
            keep = result;
        } else {
            working = result;
        }
        counter ++;
    } while ( fabs(diff) >= EPSILON);
    return result;
}

Wanna say something?