Skip to content

Instantly share code, notes, and snippets.

@icameling
Created July 26, 2022 09:05
Show Gist options
  • Save icameling/80f9e3e9fed6ba2df39f67ec231f7a04 to your computer and use it in GitHub Desktop.
Save icameling/80f9e3e9fed6ba2df39f67ec231f7a04 to your computer and use it in GitHub Desktop.
#面试 #数字开根号
float sqrt_float(float x) {
if (x < 0) {
return -1;
}
float left = x/2, right = x;
if (x < 0.5) {
left = 0;
right = x;
}
float eps = 1e-5;
while (right - left > eps) {
float mid = (left + right) / 2.0;
float mid2 = mid * mid;
if (abs(mid2 - x) < eps) {
return mid;
}
if (mid2 < x) {
left = mid;
} else {
right = mid;
}
}
return right;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment