Last active
April 27, 2019 01:07
-
-
Save spiritedRunning/ae30faee3ce4da0d2d720e55b329480a to your computer and use it in GitHub Desktop.
sqrt二分法实现
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public double mySqrt(int x, double precision) { | |
if (x == 1 || x == 0) { | |
return x; | |
} | |
float left = 0, right = x; | |
while (left <= right) { | |
float mid = left + (right - left) / 2; | |
if (Math.abs(mid * mid - x) <= precision) { | |
return mid; | |
} else if (mid > x / mid) { | |
right = mid; | |
} else { | |
left = mid; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment