01: /**
02:    Computes approximations to the square root of
03:    a number, using Heron's algorithm.
04: */
05: public class RootApproximator
06: {
07:    /**
08:       Constructs a root approximator for a given number.
09:       @param aNumber the number from which to extract the square root
10:       (Precondition: aNumber >= 0)
11:    */
12:    public RootApproximator(double aNumber)
13:    {
14:       a = aNumber;
15:       xold = 1;
16:       xnew = a;
17:    }
18: 
19:    /**
20:       Computes a better guess from the current guess.
21:       @return the next guess
22:    */
23:    public double nextGuess()
24:    {
25:       xold = xnew;
26:       if (xold != 0)
27:          xnew = (xold + a / xold) / 2;
28:       return xnew;
29:    }
30: 
31:    /**
32:       Computes the root by repeatedly improving the current
33:       guess until two successive guesses are approximately equal.
34:       @return the computed value for the square root
35:    */
36:    public double getRoot()
37:    {
38:       assert a >= 0;
39:       while (!Numeric.approxEqual(xnew, xold))
40:          nextGuess();
41:       return xnew;
42:    }
43:    
44:    private double a; // The number whose square root is computed
45:    private double xnew; // The current guess
46:    private double xold; // The old guess
47: }