, .
, 11 , 52 .
0.
, ( ), Math.getExponent . ,
- NaN , Double.MAX_EXPONENT + 1.
- , Double.MIN_EXPONENT -1.
, 1 52 . , (.. ) 1, 52 , .
public static BigInteger[] convertToFraction(double value) {
int exponent = Math.getExponent(value);
if (exponent > Double.MAX_EXPONENT) {
throw new IllegalArgumentException("Illegal parameter 'value': " + value);
}
long positiveSignificand;
if (exponent < Double.MIN_EXPONENT) {
exponent++;
positiveSignificand = Double.doubleToLongBits(value) & 0x000fffffffffffffL;
} else {
positiveSignificand = (Double.doubleToLongBits(value) & 0x000fffffffffffffL) | 0x0010000000000000L;
}
BigInteger significand = BigInteger.valueOf(value < 0 ? -positiveSignificand : positiveSignificand);
exponent -= 52;
BigInteger coefficient = BigInteger.ONE.shiftLeft(Math.abs(exponent));
if (exponent >= 0) {
return new BigInteger[] { significand.multiply(coefficient), BigInteger.ONE };
} else {
BigInteger gcd = significand.gcd(coefficient);
return new BigInteger[] { significand.divide(gcd), coefficient.divide(gcd) };
}
}