RFR: 8341470: BigDecimal.stripTrailingZeros() optimization [v42]

Raffaello Giulietti rgiulietti at openjdk.org
Sun Oct 13 13:18:16 UTC 2024


On Sat, 12 Oct 2024 17:37:25 GMT, fabioromano1 <duke at openjdk.org> wrote:

>> An optimized algorithm for `BigDecimal.stripTrailingZeros()` that uses repeated squares trick.
>
> fabioromano1 has updated the pull request incrementally with one additional commit since the last revision:
> 
>   Minor change

After the proposed modifications, which aim to clarify the numeric aspects, I'll wait for a couple of days before approval for you to commit possible last minute changes.

src/java.base/share/classes/java/math/BigDecimal.java line 5242:

> 5240:     }
> 5241: 
> 5242:     private static final double LOG_5_OF_2 = Math.log(2.0) / Math.log(5.0);

Suggestion:

    private static final double LOG_5_OF_2 = 0.43067655807339306; // double closest to log5(2)

to be sure that `LOG_5_OF_2` is the best possible, although it doesn't matter much.

src/java.base/share/classes/java/math/BigDecimal.java line 5270:

> 5268: 
> 5269:         intVal = intVal.shiftRight(powsOf2); // remove powers of 2
> 5270:         // maxPowsOf5 >= floor(log5(intVal)) >= max{n : (intVal % 5^n) == 0}

Suggestion:

        // Let k = max{n : (intVal % 5^n) == 0}, m = max{n : 5^n <= intVal}, so m >= k.
        // Let b = intVal.bitLength(). It can be shown that
        // | b * LOG_5_OF_2 - b log5(2) | < 2^(-21) (fp viz. real arithmetic),
        // which entails m <= maxPowsOf5 <= m + 1, where maxPowsOf5 is as below.
        // Hence, maxPowsOf5 >= k and is never off by more than 1 from the theoretical m.

-------------

PR Review: https://git.openjdk.org/jdk/pull/21323#pullrequestreview-2364917422
PR Review Comment: https://git.openjdk.org/jdk/pull/21323#discussion_r1798328808
PR Review Comment: https://git.openjdk.org/jdk/pull/21323#discussion_r1798329279


More information about the core-libs-dev mailing list