Skip to content

round instead of overrunning the mantissa in the Dfp long constructor - #359

Open
insaf021 wants to merge 1 commit into
apache:masterfrom
insaf021:dfp-long-constructor-round
Open

insaf021 wants to merge 1 commit into
apache:masterfrom
insaf021:dfp-long-constructor-round

Conversation

@insaf021

Copy link
Copy Markdown
Contributor

Reproduced on master, JDK 21:

new DfpField(10).newDfp(12345678901234567L)
java.lang.ArrayIndexOutOfBoundsException: arraycopy: destination index -1 out of bounds for int[4]

Dfp(DfpField, long) shifts each radix digit into the mantissa with System.arraycopy and never checks exp against mant.length. Any DfpField below 17 decimal digits has 4 radix digits (16 decimal), but a long needs up to 5, so every |x| >= 10^16 overruns, Long.MAX_VALUE and Long.MIN_VALUE included. DfpField.newDfp(long) and Dfp.newInstance(long) both land here, whereas newDfp("12345678901234567") on the same field rounds to the precision as expected.

Once the mantissa is full, the least significant digit is now shifted out and the value is rounded with it through round(), the same path the string constructor uses. The Long.MIN_VALUE +1 correction goes to that digit when one was dropped. Fields of 17 or more digits take the old path unchanged.

testLongConstructorBeyondPrecision in DfpTest checks that the long and string constructors agree on a 10-digit field. It fails on master with the exception above and passes with the fix; mvn clean verify javadoc:javadoc on legacy-core is green.

Dfp(DfpField, long) shifted every radix digit into the mantissa without
checking its length. Fields below 17 decimal digits have 4 radix digits
while a long needs up to 5, so any |x| >= 10^16 threw
ArrayIndexOutOfBoundsException. Shift the least significant digit out
once the mantissa is full and round with it, as the string constructor
does.
@Test
public void testLongConstructorBeyondPrecision() {
// 4 radix digits (16 decimal digits) cannot hold every long
final DfpField small = new DfpField(10);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The source code shows decimal digits < 13 using 4 radix digits (radix=10000). So we have configured for 16 decimal digits. But the long value 12345678901234567L has 17 digits and is reproduced as exactly the same String, yet 1234567890123456789L has 19 digits and is reproduced as a 15 digit String plus exponent. So has rounding missed a digit? Should the result be "1.234567890123457e18"?

This should show behaviour with 16, 17, 18 and 19 digit strings that expect rounding up or down when the Dfp has to round.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants