insaf021 opened a new pull request, #362:
URL: https://github.com/apache/commons-math/pull/362

   Follow-up to the string parsing issue found while reviewing #359.
   
   `Dfp(DfpField, String)` keeps one decimal digit past the mantissa and rounds 
with it:
   
       final int excp = round((striped[q] - '0') * 1000);
   
   `round()` takes its argument as a fraction of the last radix digit out of 
10000, so a single decimal digit can only ever be a multiple of 1000. Two 
things fall out of that:
   
   * a remainder of `5678` is passed as `5000`, which `ROUND_HALF_EVEN` reads 
as an exact half and takes down. On a 4 radix digit field, 
`newDfp("123456789012345678")` gives `1.2345678901234e17` where the nearest 
value is `1.2345678901235e17`.
   * every digit below the first one is dropped before `round()` sees it, so a 
tie is never broken and `FLAG_INEXACT` is never raised for them. `new 
DfpField(20).newDfp("1.0000000000000000000000001")` returns `1.` with no flags 
set.
   
   The parser copies at most `mant.length * rsize + 1` digits, so the 
information needed to decide either case was being thrown away during the copy.
   
   The fix keeps a whole radix digit of remainder instead of one decimal digit, 
which is exactly the precision `round()` works in, and records whether a 
non-zero digit was dropped below that. Anything below the four digits only 
matters as "the remainder is strictly greater", so it is tracked as a single 
sticky bit and used to nudge `n` off the two values `round()` tests exactly, 
zero and 5000. Digits dropped during the copy and digits still sitting in the 
parsed string are both covered. `striped` is now filled with `'0'` up front, 
because the rounding digits can sit past the last position the copy and the 
zero padding write.
   
   Checked against `BigDecimal.round(new MathContext(keep, HALF_EVEN))` over 
80k generated values across 7 field sizes, biased towards 0, 5 and 9 so ties 
and carries come up: 7665 disagreed before, none after. A sweep of every field 
size from 1 to 45 digits, with integer, fractional, mixed and exponent forms 
from 1 digit up to past the mantissa, also agrees throughout.
   
   `testStringConstructorRounding` in `DfpTest` pins the 16 to 19 digit bands 
with explicit expected strings, rounding up and down in each, both signs, exact 
halves going to even, a half broken by a digit inside the parsed string and by 
one far past it, the carry out of the mantissa, and the flags each case raises. 
It fails on master at the 18 digit case and passes with the fix.
   
   `mvn clean verify javadoc:javadoc` is green on legacy-core and legacy, 
checkstyle reports no violations.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to