The first thing comes to my mind is: this is a good place to use Binary search (inspired by this great tutorials.)
To find the square root of vaule
,we are searching the number
in (1..value)
where the predictor
is true for the first time. The predictor we are choosing is number * number - value > 0.00001
.
double square_root_of(double value)
{
assert(value >= 1);
double lo = 1.0;
double hi = value;
while( hi - lo > 0.00001)
{
double mid = lo + (hi - lo) / 2 ;
std::cout << lo << "," << hi << "," << mid << std::endl;
if( mid * mid - value > 0.00001) //this is the predictors we are using
{
hi = mid;
} else {
lo = mid;
}
}
return lo;
}