layman
layman

Reputation: 421

JUnit assertEqual for doubles with percentage delta

In JUnit, the assertEquals for doubles takes a delta that is absolute. But isn't a percentage value more appropriate for margin than an absolute value? When one is comparing two large values, it is likely that the error due to rounding up, if any, will result in the last significant digit irrespective of the exponent. Having an absolute delta doesn't help in such cases, does it?

It's not difficult and I wrote one, but just curious why JUnit doesn't have that function. Am I missing something?

Upvotes: 5

Views: 3076

Answers (3)

Raedwald
Raedwald

Reputation: 48692

A percentage tolerance would be no good for the case that the expected value was zero, but you were willing to accept a very small value as good enough. The cuurent API is therefore useable to all numeric values.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533680

It depends on the situation. If you have a fixed precision e.g. two decimal places you might want a delta of 0.5e-2, but if you have an unknown precision and you want significant digits you may need something more complicated like

assertEquals(expected, actual, Math.abs(expected) / 1e3);

The problem with relative error is it is harder to know if it should be relative to the expected, the actual or some combination of the two.

Upvotes: 6

LastFreeNickname
LastFreeNickname

Reputation: 1455

One can only assume as there is no clue in the JUnit API, but it targets small differences in number representations in the floating point domain (when you got a difference in the 15th position after decimal point). After all, it is by far easier to come from the absolute value version to the procentual version than the other way around.

Upvotes: 0

Related Questions