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

Method sqrt

output/java_guava/1.4.16/BigIntegerMath.java:225–258  ·  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

(BigInteger x, RoundingMode mode)

Source from the content-addressed store, hash-verified

223 */
224
225 @GwtIncompatible // TODO
226 @SuppressWarnings("fallthrough")
227 public static BigInteger sqrt(BigInteger x, RoundingMode mode) {
228 checkNonNegative("x", x);
229 if (fitsInLong(x)) {
230 return BigInteger.valueOf(LongMath.sqrt(x.longValue(), mode));
231 }
232 BigInteger sqrtFloor = sqrtFloor(x);
233 switch (mode) {
234 case UNNECESSARY:
235 checkRoundingUnnecessary(sqrtFloor.pow(2).equals(x)); // fall through
236 case FLOOR:
237 case DOWN:
238 return sqrtFloor;
239 case CEILING:
240 case UP:
241 int sqrtFloorInt = sqrtFloor.intValue();
242boolean sqrtFloorIsExact = (sqrtFloorInt * sqrtFloorInt == x.intValue()) // fast check mod 2^32
243 && sqrtFloor.pow(2).equals(x); // slow exact check
244 return sqrtFloorIsExact ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
245 case HALF_DOWN:
246 case HALF_UP:
247 case HALF_EVEN:
248 BigInteger halfSquare = sqrtFloor.pow(2).add(sqrtFloor);
249 /*
250 * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x
251 * and halfSquare are integers, this is equivalent to testing whether or not x <=
252 * halfSquare.
253 */
254 return (halfSquare.compareTo(x) >= 0) ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
255 default:
256 throw new AssertionError();
257 }
258 }
259
260 @GwtIncompatible // TODO
261 private static BigInteger sqrtFloor(BigInteger x) {

Callers 1

sqrtApproxWithDoublesMethod · 0.45

Calls 12

fitsInLongMethod · 0.95
sqrtMethod · 0.95
sqrtFloorMethod · 0.95
equalsMethod · 0.65
addMethod · 0.65
checkNonNegativeMethod · 0.45
valueOfMethod · 0.45
longValueMethod · 0.45
powMethod · 0.45
intValueMethod · 0.45
compareToMethod · 0.45

Tested by

no test coverage detected