bgarrels / hamcrest

Automatically exported from code.google.com/p/hamcrest
0 stars 0 forks source link

BigDecimalCloseTo bug in error message #201

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
I am using BigDecimalCloseTo and getting something weird in the error message. 
In the example below, I have the exact value 0.0066 and an approximation of it 
which differs by 1.01E-16.
I want to check for a precision of 1e-16, so BigDecimalCloseTo correctly 
identifies this as not close enough.
However the error message states:

"Expected: a numeric value within <1E-16> of <0.00660>
     but: <0.006599999999999899> differed by <1E-18>"

But if it only differed by 1e-18 it would be close enough. 
Looking at the code, it looks like the value calculated for the error message 
(actualDelta() method) 
also subtracts the delta (= precision), so it does:
     abs(item - value) - delta
instead of 
     abs(item - value)

    @Test
    public void test()
    {
        final BigDecimal precision = new BigDecimal(1).movePointLeft(16);
        System.out.println("Precision " + precision);

        // Exact result is: 0.0066
        // Actual result is: 0.006599999999999899
        final BigDecimal exact = new BigDecimal(66).movePointLeft(4);
        final BigDecimal actual = new BigDecimal(6599999999999899L).movePointLeft(18);

        System.out.println("Exact is " + exact);
        System.out.println("Correct is " + actual);

        System.out.println("Difference is " + exact.subtract(actual));

        final BigDecimal item = actual;
        final BigDecimal value = exact;
        final BigDecimal delta = precision;

        // This is the code that produces the value in the error message
        final BigDecimal errorMsgValue =
                item.subtract(value, MathContext.DECIMAL128).abs()
                                    .subtract(delta, MathContext.DECIMAL128).stripTrailingZeros();
        System.out.println(errorMsgValue);

        assertThat(actual, BigDecimalCloseTo.closeTo(exact, precision));
    }

Output is:
Precision 1E-16
Exact is 0.0066
Correct is 0.006599999999999899
Difference is 1.01E-16
1E-18

Original issue reported on code.google.com by alex.kar...@gmail.com on 27 Jul 2013 at 10:01

GoogleCodeExporter commented 9 years ago

Original comment by t.denley on 19 Aug 2013 at 10:17