This is the algorithm to find exact square root in java. We are going to use binary search to get exact result.
Here in blow program, We are comparing output with Math.sqrt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
package com.omt.learn.practice; public class FIndSquareRootFloat { public static void main(String s[]) { System.out.println("Square Root of 277 :"); System.out.println(squareRoot(277)); System.out.println("Square Root of 277 (Math.sqrt):"); System.out.println(Math.sqrt(277)); System.out.println("Square Root of 5 :"); System.out.println(squareRoot(5)); System.out.println("Square Root of 5 (Math.sqrt):"); System.out.println(Math.sqrt(5)); System.out.println("Square Root of 7 :"); System.out.println(squareRoot(7)); System.out.println("Square Root of 7 (Math.sqrt):"); System.out.println(Math.sqrt(7)); System.out.println("Square Root of 49 :"); System.out.println(squareRoot(49)); System.out.println("Square Root of 49 (Math.sqrt):"); System.out.println(Math.sqrt(49)); System.out.println("Square Root of 25 :"); System.out.println(squareRoot(25)); System.out.println("Square Root of 25 (Math.sqrt):"); System.out.println(Math.sqrt(25)); System.out.println("Square Root of 81 :"); System.out.println(squareRoot(81)); System.out.println("Square Root of 25 (Math.sqrt):"); System.out.println(Math.sqrt(81)); System.out.println("Square Root of 277.787 :"); System.out.println(squareRoot(277.787)); System.out.println("Square Root of 277.787 (Math.sqrt):"); System.out.println(Math.sqrt(277.787)); } public static double squareRoot(double number) { double round = 1000000000000.0d; double start = 0; double end = number; double ans = 0.0; while (start < end) { double mid = (start + end) / 2; double midXmid = (mid * mid); if (midXmid == number) { return Math.round(mid * round) / round; } else if (midXmid < number) { ans = mid; start = mid + 0.00000000000001; } else { end = mid - 0.00000000000001; } } return Math.round(ans * round) / round; } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
Square Root of 277 : 16.643316977093 Square Root of 277 (Math.sqrt): 16.64331697709324 Square Root of 5 : 2.2360679775 Square Root of 5 (Math.sqrt): 2.23606797749979 Square Root of 7 : 2.645751311065 Square Root of 7 (Math.sqrt): 2.6457513110645907 Square Root of 49 : 7.0 Square Root of 49 (Math.sqrt): 7.0 Square Root of 25 : 5.0 Square Root of 25 (Math.sqrt): 5.0 Square Root of 81 : 9.0 Square Root of 25 (Math.sqrt): 9.0 Square Root of 277.787 : 16.666943331037 Square Root of 277.787 (Math.sqrt): 16.666943331037036 |
To get more details about how square root has been implemented by Math.sqrt() then read below article
https://www.quora.com/How-do-computers-compute-the-square-root-of-something