4

assertEquals for doubles is deprecated. I found that the form with Epsilon should be used. It is because of impossible 100% strictness of doubles. But anyway I need to compare two doubles (expected and actual result), but I don't know how to do it.

At the moment my test looks like:

@Test
public void testCalcPossibleDistancePercentageCount() {
    int percentage = 100;
    assertEquals("Wrong max possible value for %" + percentage, 110.42, processor.calcPossibleValue(percentage));
    percentage = 75;
    /*corresponding assertions*/
}

Here are 3 double values I receive and which I want to check with JUnit: 110.42, 2760.5 and 10931.58. How should JUnit test look like with assertions for them? I receive them as a result of calculation in a method:

processor.calcPossibleValue(allowed_percentage){return /*Some weird formulae here*/;}
4

4 回答 4

11

You need to add a fourth parameter to the assertEquals call: the threshold within which two doubles should be considered "equal". Your call should look like this:

assertEquals("Wrong max possible value for %" + percentage, 110.42,
        processor.calcPossibleValue(percentage), 0.01);

The above call would indicate that if the value returned by processor.calcPossibleValue(percentage) is within ± 0.01 of 110.42, then the two values are considered equal. You can change this value to make it as small as is necessary for your application.

See the JUnit documentation for more information.

于 2012-08-04T12:57:53.107 回答
1

Java double 使用IEEE 754 64 位格式。这种格式有 52 个尾数位。在比较 2 个值时,epsilon 应考虑预期值的大小。

例如, 0.01 可能对 110.42 有效,但如果预期值 > 2 52则无效。2 52的量级太大以至于0.01 会因为精度而丢失(即只有52 位尾数位)。例如,2 52 + 0.01 == 2 52

考虑到这一点,epsilon 应该缩放到预期值。例如,期望值 ÷ 2 52 - 3或 110.42 ÷ 2 52 - 3 = 1.96... x 10 -13。我选择了 2 52 - 3,因为这将在尾数的 3 个最低有效位中给出一个容差。

一个警告是,如果预期值为 0.0,则此公式将 epsilon 计算为 0.0,这对于特定情况可能过于严格。

另一个注意事项是不处理 NaN 和 ±∞。

于 2013-08-01T18:16:25.397 回答
1

断言已弃用

assertTrue("message like not equal ",expectedresult-actual == 0);
于 2019-04-26T16:20:05.690 回答
1
Assert.assertTrue("Not equals", expectedDouble -  actualDouble == 0);

无需涉及 epsilon 或 delta。

于 2017-01-16T20:02:51.903 回答