MCPcopy Create free account
hub / github.com/antlr/codebuff / sqrt

Method sqrt

output/java_guava/1.4.16/IntMath.java:279–312  ·  view source on GitHub ↗

Returns the square root of x, rounded with the specified rounding mode. @throws IllegalArgumentException if x < 0 @throws ArithmeticException if mode is RoundingMode#UNNECESSARY and sqrt(x) is not an integer

(int x, RoundingMode mode)

Source from the content-addressed store, hash-verified

277 */
278
279 @GwtIncompatible // need BigIntegerMath to adequately test
280 @SuppressWarnings("fallthrough")
281 public static int sqrt(int x, RoundingMode mode) {
282 checkNonNegative("x", x);
283 int sqrtFloor = sqrtFloor(x);
284 switch (mode) {
285 case UNNECESSARY:
286 checkRoundingUnnecessary(sqrtFloor * sqrtFloor == x); // fall through
287 case FLOOR:
288 case DOWN:
289 return sqrtFloor;
290 case CEILING:
291 case UP:
292 return sqrtFloor + lessThanBranchFree(sqrtFloor * sqrtFloor, x);
293 case HALF_DOWN:
294 case HALF_UP:
295 case HALF_EVEN:
296 int halfSquare = sqrtFloor * sqrtFloor + sqrtFloor;
297 /*
298 * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x
299 * and halfSquare are integers, this is equivalent to testing whether or not x <=
300 * halfSquare. (We have to deal with overflow, though.)
301 *
302 * If we treat halfSquare as an unsigned int, we know that
303 * sqrtFloor^2 <= x < (sqrtFloor + 1)^2
304 * halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1
305 * so |x - halfSquare| <= sqrtFloor. Therefore, it's safe to treat x - halfSquare as a
306 * signed int, so lessThanBranchFree is safe for use.
307 */
308 return sqrtFloor + lessThanBranchFree(halfSquare, x);
309 default:
310 throw new AssertionError();
311 }
312 }
313
314 private static int sqrtFloor(int x) {
315 // There is no loss of precision in converting an int to a double, according to

Callers 8

sqrtMethod · 0.95
sqrtFloorMethod · 0.45

Calls 4

sqrtFloorMethod · 0.95
lessThanBranchFreeMethod · 0.95
checkNonNegativeMethod · 0.45

Tested by

no test coverage detected