Domanda di colloquio di Meta

How to implement Sqrt(double k) efficiently?

Risposte di colloquio

Anonimo

4 feb 2012

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

Anonimo

3 apr 2012

double sqrt2(double num) { double i = 0, j = num, mid; if(j 0.00001) { if(mid*mid > num) j = mid; else i = mid; mid = (i+j)/2.0; } return mid; }

2

Anonimo

11 gen 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

Anonimo

30 dic 2011

Binary search, start with reasonable range and shrinking the range until precision level is satisfied

Anonimo

19 gen 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?