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

Method bigToDouble

output/java_guava/1.4.17/DoubleUtils.java:94–136  ·  view source on GitHub ↗
(BigInteger x)

Source from the content-addressed store, hash-verified

92
93
94 static double bigToDouble(BigInteger x) {
95 // This is an extremely fast implementation of BigInteger.doubleValue(). JDK patch pending.
96 BigInteger absX = x.abs();
97 int exponent = absX.bitLength() - 1;
98 // exponent == floor(log2(abs(x)))
99 if (exponent < Long.SIZE - 1) {
100 return x.longValue();
101 } else if (exponent > MAX_EXPONENT) {
102 return x.signum() * POSITIVE_INFINITY;
103 }
104
105 /*
106 * We need the top SIGNIFICAND_BITS + 1 bits, including the "implicit" one bit. To make rounding
107 * easier, we pick out the top SIGNIFICAND_BITS + 2 bits, so we have one to help us round up or
108 * down. twiceSignifFloor will contain the top SIGNIFICAND_BITS + 2 bits, and signifFloor the
109 * top SIGNIFICAND_BITS + 1.
110 *
111 * It helps to consider the real number signif = absX * 2^(SIGNIFICAND_BITS - exponent).
112 */
113 int shift = exponent - SIGNIFICAND_BITS - 1;
114 long twiceSignifFloor = absX.shiftRight(shift).longValue();
115 long signifFloor = twiceSignifFloor >> 1;
116 signifFloor &= SIGNIFICAND_MASK; // remove the implied bit
117
118 /*
119 * We round up if either the fractional part of signif is strictly greater than 0.5 (which is
120 * true if the 0.5 bit is set and any lower bit is set), or if the fractional part of signif is
121 * >= 0.5 and signifFloor is odd (which is true if both the 0.5 bit and the 1 bit are set).
122 */
123 boolean increment = (twiceSignifFloor & 1) != 0
124&& ((signifFloor & 1) != 0 || absX.getLowestSetBit() < shift);
125 long signifRounded = increment? signifFloor + 1 : signifFloor;
126 long bits = (long) ((exponent + EXPONENT_BIAS)) << SIGNIFICAND_BITS;
127 bits += signifRounded;
128 /*
129 * If signifRounded == 2^53, we'd need to set all of the significand bits to zero and add 1 to
130 * the exponent. This is exactly the behavior we get from just adding signifRounded to bits
131 * directly. If the exponent is MAX_DOUBLE_EXPONENT, we round up (correctly) to
132 * Double.POSITIVE_INFINITY.
133 */
134 bits |= x.signum() & SIGN_MASK;
135 return longBitsToDouble(bits);
136 }
137
138 /**
139 * Returns its argument if it is non-negative, zero if it is negative.

Callers 1

sqrtApproxWithDoublesMethod · 0.95

Calls 1

longValueMethod · 0.45

Tested by

no test coverage detected