1
public static double sqrt(double c)
{
    if (c < 0) return Double.NaN;
    double t = c;                          // line 1
    double err = 1e-15;                    // line 2
    while (Math.abs(t - c/t) > err * t)    // line 3
        t = (c/t + t) / 2.0;           // line 4
    return t;
}

Q1: I am confused by the variable t in line1 and line 4: since t = c, then c/t = 1, what does line 4 mean?

Q2: In line 3, what's the purpose to check?

I searched "Newton's method" and got several explanation, but I still could not understand. May I request an straight forward explanation here?

AntonH
  • 6,359
  • 2
  • 30
  • 40
Nick
  • 8,451
  • 13
  • 57
  • 106

2 Answers2

3

Q1: Note that t changes with each iteration of the loop, so while c/t==1 initially, it won't after that.

Q2: We want the loop to continue until we get an answer "close enough", as defined by err.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
2

The Newton's method is used to approximate real valued functions' roots. See here.

When you are calculating the root to a double value you are actually trying to solve for F(x) = X^2 - C where C is the double and you would be trying to find the x that makes the equation zero.

Now the Newton's Method approximates this by a series of guesses. By each guess(as this function has the appropriate properties), we get closer to the square root. The incremental approximation is actually calculating the tangent to the graph at each guess(t) and then choosing that as a guess at that point and moves closer in steps(c/t + t)/2. At a certain point we get very close and we don't want the function to go on forever so we have line 3 to check that our next estimation has a certain distance from the current approximation. If the next approximation is closer than err*t we don't bother continuing. We are close enough.

Farhad Alizadeh Noori
  • 2,276
  • 17
  • 22