Skip to content

Instantly share code, notes, and snippets.

@spiritedRunning
Last active April 27, 2019 01:07
Show Gist options
  • Save spiritedRunning/ae30faee3ce4da0d2d720e55b329480a to your computer and use it in GitHub Desktop.
Save spiritedRunning/ae30faee3ce4da0d2d720e55b329480a to your computer and use it in GitHub Desktop.
sqrt二分法实现
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