Calculate delta value for assertEquals in Junit

Asked

Viewed 1,526 times

1

Greetings.

How best to calculate the delta value of Junit’s assertEquals(message, expected, actual, delta) method?

1 answer

3


The purpose of the parameter delta of that method is determine the maximum value of the difference between the numbers expected and actual so that they are considered the same value.

For example, let’s assume that you have a routine that returns a floating point number double. You expect the value 2.5, but the routine returns 2.499999999999.

These problems can occur precisely because of the known dilemma of numerical representation using bits, so it is expected that a loss of precision occurs in a sequence of numerical operations.

Another source of this difference may be rounding made during calculations.

In most cases you can tolerate these small differences, especially when the results are not used as input for other processes and the decimals are not very relevant.

So basically you need to determine how many decimal places matter in the context of your system. For example, a personal financial system can tolerate calculation failures from the third decimal place, because in Real the accuracy is given in cents. However, in financial institutions or some types of business (such as gas stations) may need more precision, using 3 or 4 homes depending on the calculation.

So, for example, if you pass a delta value of 0.01, Junit will throw a mistake if abs(expected - actual) > 0.01.

In general, for financial systems, this accuracy must be specified somewhere, as it is the centerpiece of business.

However, I would not recommend relying on this kind of precision calculation when in many cases it is possible to bypass this.

First, see if the use of double is necessary. A lot of people use these variables without thinking when the values could actually be integer like int or long.

Second, for calculations where accuracy is important, consider using BigDecimal, that although it is slower it does not suffer from binary representation problems.

  • 1

    Your reply was excellent. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.