/**
* Approximate the square root using the Newton-Rhapson Method
*
* @param n
* the number to get the square root of
* @param tolerance
* max distance between square root estimates
* @throws InvalidArgumentException
* thrown if edge cases are passed that cannot be approximated
*/
private double approximateSquareRoot(double n, double tolerance) throws IllegalArgumentException {
if (n == Double.NaN) {
throw new IllegalArgumentException(
"Cant approximate square root of Double.NaN");
}
if (n == Double.NEGATIVE_INFINITY || n == Double.POSITIVE_INFINITY) {
throw new IllegalArgumentException(
"Cant approximate square root of Infinity");
}
if (n == 0) {
return 0;
}
double root = n / 2;
while (Math.abs(root - (n / root)) > tolerance) {
root = 0.5 * (root + (n / root));
}
return root;
}