previous | start | next

File RootApproximator.java

1 /**
2     Computes approximations to the square root of
3     a number, using Heron's algorithm
4 */
5 public class RootApproximator
6 {
7    /**
8        Constructs a root approximator for a given number
9       @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        Compute 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        Compute 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       while (!Numeric.approxEqual(xnew, xold))
39          nextGuess();
40       return xnew;
41    }
42    
43    private double a; // the number whose square root is computed
44    private double xnew; // the current guess
45    private double xold; // the old guess
46 }


previous | start | next