Search code examples
javasqrtnewtons-method

A version of Newton Raphson (Newton's method)


public class Sqrt
  {
     public static void main(String[] args)
       {
           double EPS = 1E-15;
           double c = Double.parseDouble(args[0]);
           double t = c;
              while (Math.abs(t - c/t) > t * EPS)
                      { t = (c/t + t) / 2.0; }
              System.out.println(t);
          }
      } 

Above is one version of Newton Raphson i found in Java. I suppose it works but I'm having a hard time wrapping my head around how it actually works. { t = (c/t + t) / 2.0; } really confuses me.

I'm familiar with x_n+1 = x_n - f(x_n)/ f'(x_n) but not the one implemented in the code above..


Solution

  • To be able to apply the Newton-Raphson-method you have to find a function, for which the zero is the solution you are looking for. In the case of square-root this is:

    f(x) = x^2 - c
    

    Now if you find a x with f(x) = 0 you have found a square root of c.

    f'(x) = 2*x
    

    so

    x - f(x)/f'(x) = x - ( (x^2 - c) / (2*x) ) = 1/2 * (x + c/x)
    

    which is where your (c/t + t) / 2.0 comes from.