4

I have a very simple Java test case which calls Math.exp(double) and then StrictMath.exp(double) and for a reason I can't understand the result is different on Java 8 despite the fact that from JDK source code it appears that Math.exp simply delegates to StrictMath.exp.

public static void main(String[] args) {
    Properties p = System.getProperties();
    System.out.println(p.get("java.runtime.version"));
    System.out.println(p.get("java.specification.version"));
    System.out.println(Math.exp(1d));
    System.out.println(StrictMath.exp(1d));
}

result on Java 8:

1.8.0_66-b18
1.8
null
2.718281828459045
2.7182818284590455

and on Java 7:

1.7.0_21-b11
1.7
2.7182818284590455
2.7182818284590455

Any pointers appreciated, more out of curiosity than any real issue.

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Ian
  • 41
  • 1

1 Answers1

2

This question is essentially the opposite of the question Joe linked to: java.lang.Math.log replaced by intrinsic call, why not java.lang.Math.exp()?

Before revision 6759698e3140 Math.exp() was not replaced at runtime by an intrinsic call, meaning it delegated to StrictMath.exp(). After that revision (and therefore all of Java 8) it is possible that Math.exp() will give a different result because the JVM will optimize the calls.

Conceptually you can think of Math as providing "fast" functions, and StrictMath providing "correct" functions. Math falls back to StrictMath when it can do no better, but the guarantees about Math's behavior are weaker than StrictMath's, and therefore can be optimized (potentially at the cost of some limited correctness) more than StrictMath.

Community
  • 1
  • 1
dimo414
  • 47,227
  • 18
  • 148
  • 244