简体   繁体   中英

Exact mixed comparison BigInteger and double in Java

Just noticed that Python and JavaScript have exact comparison. Example in Python:

>>> 2**1023+1 > 8.98846567431158E307
True

>>> 2**1023-1 < 8.98846567431158E307
True

And JavaScript:

> 2n**1023n+1n > 8.98846567431158E307
true

> 2n**1023n-1n < 8.98846567431158E307
true

Anything similar available for Java, except converting both arguments to BigDecimal?

Preliminary answer, ie verbal solution sketch:

I am skeptical about a solution that would convert to BigDecimal, since this conversion results in a shift of the base from base=2 to base=10. As soon as the exponent of the Java double floating point value is different from the binary precision, this leads to additional digits and lengthy pow() operations, which one can verify by inspecting some open source BigDecimal(double) constructor implementation.

One can get the mantissa via Double.doubleToRawLongBits(d). If the Java double floating point value is not a sub-normal all that needs to be done is (raw & DOUBLE_SNIF_MASK) + (DOUBLE_SNIF_MASK+1) where 0x000fffffffffffffL This means the integer Java primitive type long should be enough to carry the mantissa. The challenge is now to perform a comparison taking the exponent of the float also into account.

But I must admit I didn't have time yet to work out some Java code. I have also in mind some optimizations using bigLength() of the other argument, which is in this setting a BigInteger. The use of bitLength() would speed up the comparison. A simple heuristic can implement a fast path, so that the mantissa can be ignored. Already the exponent of the double and the bitLength() of the BigInteger give enough information for a comparison result.

As soon as I have time and a prototype running, I might publish some Java code fragment here. But maybe somebody faced the problem already. My general hypothesis is that a fast or even ultra fast routine is possible. But I didn't have much time to search the inte.net and to find an implementation, thats why I defered the problem to stack overflow, maybe somebody else had the same problem as well and/or might point to a complete solution?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM