• Breaking News

    Saturday, 31 October 2015

    Finding Square Root of given number


    In mathematical form, the problem is :
    Given x>0, find y such that y2=x.

    If we rethink the problem then it means , if y is the square root of x, then y2=x, so x/y=y.
     This gives us an idea for an algorithm:
    1. Guess some value of y , say g.
    2. Compute x/g and test.
    3. If x/g is not close enough to g. then try a better guess.

    The bold words are the essence of this algorithm(Recursive algorithm).So, lets define the steps more clearly.

    1.Guess some value of g. Take g = 1.

    double sqrt(double x) {
    
       return test(x, 1);
    
    }
    
    2. Test is the method which will compute value of x/g.

    double test(double x, double g) {
    
       if closeEnough(x/g, g)
    
          return g;
    
       else
    
          return test(x, betterGuess(x, g));
    
    }
    
    3.This is the main step where we will define what close enough means for us and what a good guess can be.

    boolean closeEnough(double a, double b) {
    
       return (Math.abs(a - b) < .001);
    
    }
    
    double betterGuess(double x, double g) {
    
       return ((g + x/g) / 2);
    
    }
    
    
    
    Here i had taken precision value to be '0.001'. You can take it as per your requirement/comfort or i would say how precise you want to calculate the square root.

    And in case of better guess, dividing by half is best option since we taking the mid value of range from 'g' to 'x/g'.

    Following is the program written in java implementing the above algorithm.

    import java.util.Scanner;
    
    public class SquareRoot {
    
     private static Scanner in = new Scanner(System.in);
     
     public static void main(String[] args) {
       
      double x  = in.nextDouble();
      
      System.out.print(test(x,1));
      
     }
     
     private static double test(double x, double g) {
      
      if(closeEnough(x/g,g))
       return g;
      else
       return test(x,betterGuess(x,g));
     }
     
     private static double betterGuess(double x, double g) {
      return ((x/g+g)/2);
     }
     
     private static boolean closeEnough(double a, double b) {
      return (Math.abs(a-b)<.001);
     }
    
    }
    

    No comments:

    Post a Comment