File size: 633 Bytes
9438a57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.*;

/**
 * Square Root
 * 
 * Newton-Raphson method implementation.
 * 
 * 
 * Input:
 *     x: A float
 *     epsilon: A float
 * 
 * Precondition:
 *     x >= 1 and epsilon > 0
 * 
 * Output:
 *     A float in the interval [sqrt(x) - epsilon, sqrt(x) + epsilon]
 * 
 * Example:
 *     >>> sqrt(2, 0.01)
 *     1.4166666666666665
 *
 * @author derricklin
 */
public class SQRT {
    public static double sqrt(double x, double epsilon) {
        double approx = x / 2d;
        while (Math.abs(x-approx*approx) > epsilon) {
            approx = 0.5d * (approx + x / approx);
        }
        return approx;
    }
}