binary search is not a good approach, too slow. compare to that newton's method is simple and fast.
double sqrt_newton(double v) {
double x, nx = 1;
while (abs(nx - x) > 1e-9) {
x = nx;
nx = (v / x + x) / 2;
}
return nx;
}
2
Anoniem
11 jan 2012
You could also use Newton's Method. It might be a bit (just a bit) less efficient, but it will work with every function, not just sqrt.
en.wikipedia.org/wiki/Newton's_method
1
Anoniem
30 dec 2011
Binary search, start with reasonable range and shrinking the range until precision level is satisfied
Anoniem
19 jan 2012
i came up with a iterative algorithm bu having problem with the precision. for example, i get to this solution 2.236068 instead of 2.23606798 for sqrt(5) using double numbers, any ideas why?