javafloating-point

Product of two exact represented doubles. Is exact?


Let's say that we have two double in Java:

double a, b; // a and b are any decimals that have exact representation in IEEE-754

Is it guaranteed that a * b and a / b returns exact result and has exact representation in double if it does not exceed +/- INF?


Solution

  • No. Imagine two numbers a and b that meet the requirement. That means that a op b is exact. Now continue the process as below.

    double a = 1.5; // exact
    double b = 1.5; // exact
    
    BigDecimal c = new BigDecimal("1.5");
    BigDecimal d = new BigDecimal("1.5");
    
    for (int i = 0; i < 100; i++) {
        if (!new BigDecimal(a).equals(c)) {
          System.out.printf("Diff at loop %d: %.50f vs %.50f\n",
            i, c, new BigDecimal(a));
          break;
        }
        a *= b; // a is presumed to be exact each time based on assumption
        c = c.multiply(d);
    }
    

    prints

    Diff at loop 33: 970739,73736647568875923752784729003906250000000000000000 vs
                     970739,73736647563055157661437988281250000000000000000000