Same Java version produces different output for double value

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.

>Solution :

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();

Leave a Reply