Tuesday, May 8, 2012

Finding Square root without using sqrt function in java


public class Maths {

      public double sqrt(double number) {
            if (number < 0) {
                  return Double.NaN;
            }
            if (number == 0) {
                  return number;
            }
            double epsilon = 1e-15;
            double root = 0;
            double sqrt = number;
            while (Math.abs(sqrt - (root = (number / sqrt))) > epsilon * sqrt) {
                  sqrt = (root + sqrt) / 2.0;
            }
            return sqrt;
      }

      public static void main(String[] args) {
            double num = 2;
            Maths m = new Maths();
            double sqrt = m.sqrt(num);
            System.out.println("SQRT is " + sqrt);
      }
}

No comments:

Post a Comment