Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

Math.pow yields different result depending on java version

I'm running the following code on a JDK Version 1.7.0_60:

System.out.println(Math.pow(1.5476348320352065, (0.3333333333333333)));

The result is: 1.1567055833133086

I'm running exactly the same code on a JDK Version 1.7.0.

The result is: 1.1567055833133089

I understand that double is not infinitely precise, but was there a change in the java spec that causes the difference?

PS: Because we use a legacy system, Big Decimal is not an option.

Edit: I was able to track down the time of the change: It was introduced in the JDK Version 1.7.0_40 (as compared to Version 1.7.0_25).

question from:https://stackoverflow.com/questions/25404088/math-pow-yields-different-result-depending-on-java-version

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

but was there a change in the java spec that causes the difference?

No.* According to the Javadocs for Math.pow, a difference of up to one ULP (Unit in the Last Place) is permitted. If we take a look at your two values:

System.out.printf("%016x
", Double.doubleToLongBits(1.1567055833133086));
System.out.printf("%016x
", Double.doubleToLongBits(1.1567055833133089));

we get:

3ff281ddb6b6e675
3ff281ddb6b6e676

which indeed differ by one ULP.

What you're seeing is probably due to slight differences in the sequence of floating-point instructions used by the JDK/JVM to implement these operations.


* At least, not so far as I know!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...