Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
Why does JUnit assertEquals( -0.0, 0.0 ) fail?

I'm working with JUnit 5 in Java SE 11 and discovered that assertEquals(-0.0,0.0) fails. Why is that? Java itself is perfectly happy with "-0. == 0.". Sample code follows.

double  dVar1   = 0;
double  dVar2   = -dVar1;
System.out.println( dVar1 == dVar2 ); // true
System.out.println( -0. == 0. );      // true
assertEquals( dVar1, dVar2, .00001 ); // passes
assertEquals( 0.0, -0.0, .0001 );     // passes
assertEquals( 0.0, -0.0 );            // fails
assertEquals( dVar1, dVar2 );         // fails
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Java has no problem with -0 and 0. But in assertEquals method use this method from Double class to convert params to longBits and the reterned values are not the same.

 public static long doubleToLongBits(double value) {
        long result = doubleToRawLongBits(value);
        // Check for NaN based on values of bit fields, maximum
        // exponent and nonzero significand.
        if ( ((result & DoubleConsts.EXP_BIT_MASK) ==
              DoubleConsts.EXP_BIT_MASK) &&
             (result & DoubleConsts.SIGNIF_BIT_MASK) != 0L)
            result = 0x7ff8000000000000L;
        return result;
    }

In your case you have to use the first assertEquals(double expected, double actual, double delta) which based on math operation: return doublesAreEqual(value1, value2) || Math.abs(value1 - value2) <= delta

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!