public final class Sqrt { public static final double EPSILON = Sqrt.getDouble ("epsilon", 1e-9); // Sqrt using Newton's method public static double sqrt (final double x) { assert x>=0; double t = 1.0D; // a dumb guess for (;;) { // Improve the current guess, t, with a closer one final double t1 = (x/t + t) / 2.0; // For purposes of tracing the algorithm, ... System.out.printf ("sqrt %.2f %.6f %.6f %.2e%n", x , t1, Math.sqrt(x), Math.abs(Math.sqrt(x)-t1)); // Stop iterating when there is little improvement if (Math.abs (t1-t) < EPSILON) break; t = t1; } return t; } public static void main (final String[] args) { for (String arg: args) { sqrt (Double.parseDouble (arg)); } } // A function get a double from the system properites, if one is provided. private static double getDouble (final String name, final double defaultValue) { assert name!=null && name.length()>0; final String value = System.getProperty (name); if (value==null) return defaultValue; double d; try { d = Double.valueOf(value.trim()).doubleValue(); } catch (final NumberFormatException ex) { d = defaultValue; } return d; } }