The other day I ran into a question in Stackoverflow asking how to implement square-root calculation. I started googling it up and some implementations seemed to me very cumbersome but then I found Newton’s method which is pretty easy to implement. Translating it to Java was a matter of a few lines of code:
class Sqrt {
public static void main(String[] args) {
System.out.println(sqrt(17)); // 4.123105985575862
}
final static double DELTA = 0.0001;
/**
* Newton's method:
*
* X1 = X0 - f(x)/f'(x)
* x^2 = num
* f(x) = x^2 - num
* f'(x) = 2*x
*
* X1 = X0 - (X0^2 - num) / 2*X0
* ...
* Xn = Xn-1 - ((Xn-1)^2 - num)/2Xn-1
*
* Stop condition: |num - (Xn)^2| < DELTA
* */
public static double sqrt(double num) {
double x = num / 2; // starting point
while(Math.abs(num - x * x) > DELTA) {
x = x - ((x * x - num) / (2 * x));
}
return x;
}
}