0

I have a long sum of doubles that produces an output. Problem comes when I execute the tests E2E my local environment gets a result with certain amount of decimals but in the dev machine despite it has the same architecture and same java version the decimals do not match for certain sums.

For instance:

match failed: EQUALS
  $ | not equal (NUMBER:NUMBER)
  6764785.117418662 ---> dev
  6764785.11741866  ---> Local

match failed: EQUALS
  $ | not equal (NUMBER:NUMBER)
  9.7787576643837 ---> dev
  9.778757664383699 ---> Local

match failed: EQUALS
  $ | not equal (NUMBER:NUMBER)
  2.0465350497710526 ---> dev
  2.046535049771075 ---> Local

These are just some examples.

I am using openjdk version "11.0.15" 2022-04-19 from temurin

I also tried another java version but it keeps happening the same. Any idea of what might i be doing wrong? Also using intelliJ latest version.

Vml11
  • 361
  • 1
  • 2
  • 11
  • 4
    Never trust on double equality in code. Either use a smal allowed delta (this is what JUnit's `assertEquals(double, double, double)` does), or use `BigDecimal`. – Rob Spoor Nov 23 '22 at 15:03
  • 3
    Can you please provide an [mre]? – Lino Nov 23 '22 at 15:03
  • This might also be a HW difference - as Rob said, always count with precision issues in floating point math (which this is). – Thomas Nov 23 '22 at 15:05
  • Yeah it seems i might need to go with Delta checks. In any case does someone know why this difference can happen on doubles? Minimal reproducible example is kinda hard to tell just a bunch of doubles that i sum. I guess Java might take some of the decimals as BigDecimal and when they sum the precision is different. – Vml11 Nov 23 '22 at 15:09
  • 1
    Because floating point numbers are like this. Check [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Chaosfire Nov 23 '22 at 15:14

1 Answers1

3

Our computers cannot store exact representation of double type. They must be rounded to be saved. That's why comparing them directly with == might produce unexpected results. You can read more here about this topic.

Example of correct comparison of doubles in plain java:

double epsilon = 0.000001d;
assertThat(Math.abs(d1 - d2) < epsilon).isTrue();
Pekinek
  • 298
  • 1
  • 9