Created
July 26, 2022 09:05
-
-
Save icameling/80f9e3e9fed6ba2df39f67ec231f7a04 to your computer and use it in GitHub Desktop.
#面试 #数字开根号
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
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