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); }
double test(double x, double g) { if closeEnough(x/g, g) return g; else return test(x, betterGuess(x, g)); }
boolean closeEnough(double a, double b) { return (Math.abs(a - b) < .001); } double betterGuess(double x, double g) { return ((g + x/g) / 2); }
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