Calculate delta value for assertEquals in JUnit

1

Greetings.

What is the best way to calculate JUnit's assertEquals (message, expected, current, delta) delta value?

    
asked by anonymous 18.04.2016 / 21:09

1 answer

2

The purpose of the delta parameter of this 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 say you have a routine that returns a floating point number double . You expect the 2.5 value, but the routine returns 2.499999999999 .

These problems can accurately occur because of the known dilemma of numerical representation using bits, so it is expected that a loss of precision will occur 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 to other processes and the decimal places are not 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 greater precision, using 3 or 4 houses depending on the calculation.

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

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

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

First, see if double usage is required. Many people use these variables without thinking when values could actually be integers like int or long .

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

    
19.04.2016 / 06:48