How is the square root function implemented?
Simple implementation using Binary Search with C++
double root(double n){
// Max and min are used to take into account numbers less than 1
double lo = min(1, n), hi = max(1, n), mid;
// Update the bounds to be off the target by a factor of 10
while(100 * lo * lo < n) lo *= 10;
while(100 * hi * hi > n) hi *= 0.1;
for(int i = 0 ; i < 100 ; i++){
mid = (lo+hi)/2;
if(mid*mid == n) return mid;
if(mid*mid > n) hi = mid;
else lo = mid;
}
return mid;
}
Note that while
loop is most common with the binary search but Personally I prefer using for
when dealing with decimal numbers, it saves some special cases handling and gets pretty accurate result from small loops like that 1000
or even 500
(Both will give the same result for almost all numbers but just to be safe).
Edit: Check out this Wikipedia article for various -special purpose- methods specialized in computing the square root.
Edit 2: Apply updates suggested by @jorgbrown to fix the function in case of input less than 1. Also, apply optimization to make the bounds off the target root by a factor of 10