简体   繁体   中英

How to test for equality of float/double in JUnit?

The assertEquals(double,double) method is justifiably deprecated. Is there an alternate and/or different approach baked into junit - or do I roll my own tiny extension

  static boolean assertEquals(double d1, double d2) {
    return Math.abs(d1 - d2) < 1e-8;
}

是的,请改用assertEquals(double expected, double actual, double delta)

In the case of JUnit, there is already made functions.

But in other type of Java code, other than JUnit Test cases, IBM has a recommendation for comparing two floats, using division rather than subtraction - this makes it easier to select an epsilon that works for all ranges of input.

if (abs(a/b - 1) < epsilon)

As for the value of epsilon, I would use 5.96e-08 as given in this Wikipedia table , or perhaps 2x that value.

(see comparing float/double values using == operator )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM