2

I am trying to create an assert equals (double, double, epsilon) method. I created it and for some reason when I run my tester, the method is failing.

public static void assertEquals(double expect, double actual, double epsilon){
    totalAssertMethods ++;
    double difference = (Math.abs(expect - actual));
    if (difference <= epsilon){

    } else {
        totalAssertMethodsFailures ++;
        Throwable throwable = new Throwable("Error: Expected X +/-E, found Y");
        throwable.printStackTrace();
    }
}

I think the problem is, is that the difference between expect and actual in the test is only different from epsilon by approx 0.000001. Does anyone know how to go about fixing this?

SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
J. Doe
  • 57
  • 5
  • What are your input values? – shmosel Jan 29 '16 at 07:36
  • expected = 0.123456 and actual = 0.1234571 – J. Doe Jan 29 '16 at 07:37
  • Doens't that mean your method is actually working? The difference is 0.0000011 (> 0.000001). But this kind of comparison is always very tricky because of rounding errors. – cvesters Jan 29 '16 at 07:38
  • I want this to fail, I have a counter that counts failed tests, it is expecting four, but it is counting this as a passed test so I am getting an error saying the tests failed is one short. – J. Doe Jan 29 '16 at 07:41

2 Answers2

1

Try to round off your values to a certain precision:

double difference = Math.round(Math.abs(expect - actual) * 100000D) / 100000D;

Do the same thing for epsilon also.

double finalEpsilon = Math.round(epsilon * 100000D) / 100000D;
user2004685
  • 9,548
  • 5
  • 37
  • 54
  • Can you share the values of `difference` and `finalEpsilon`? – user2004685 Jan 29 '16 at 07:45
  • difference = -0.0000011 final epsilon = 0.000001 – J. Doe Jan 29 '16 at 07:50
  • In the above case the `difference` is -ve and `epsilon` is +ve and hence it will go inside the `if` condition and not the `else`. Try to use `Math.round` to round the results. Solution updated. – user2004685 Jan 29 '16 at 07:53
  • Figured it out, for some reason when I was saving my file, it wasn't over writing my old file, so when I would compile the same error kept showing up. Sorry for the inconvenience everyone, but thanks for the good advice! – J. Doe Jan 29 '16 at 08:01
0

A bit late, but maybe usefull to others: you can use the assertj AbstractDoubleAssert now:

assertThat(actual).isCloseTo(expected, Percentage.withPercentage(0.999999));
Tom Van Rossom
  • 1,440
  • 10
  • 18