Tags

Reference: http://www.careercup.com/question?id=13406676

There is a good idea to implement sqrt(): Newton’s method.

Wikipedia: https://en.wikipedia.org/wiki/Newton’s_method

CODE:

</pre>
float SquareRoot(float a)
 {
   float x=0;
   if(a>=0)
 {
   x=a;
 for(int i=0;i<30;i++)
 {
    x=(((x*x)+a)/(2*x));
   }
    return x;
   }
 }

If we want to get mth roots of x, x^m – a= 0

f(x) = x^m - af'(x) = mx^{m-1}

using Newton’s method,

x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)}

x_{n+1} = x_n - \frac{x_n^m-a}{mx_n^{m-1}}

in this case, m=2

x=(x^2+a)/2x;

Advertisements