This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
strictfp is used if you want your program to produce identical floating point results on all platforms you run it on. If you do not use strictfp then the compiler/jvm is free to optimise the floating point arithmetic for the particular platform the program is compiled/run on.
Think about this code: float x, a, b, c; .... x = a/b/c;
This is translated by the Java compiler into these expressions: float temp = a/b; x = temp/c;
In the general case, floating point division gives answers like 1/3 that cannot be expressed exactly in floating point, so the answers are rounded to the nearest value that can be represented in floating point format.
x, a, b, and c are always stored in IEEE-754 standard float format and look the same on any Java platform. If the hardware on your computer uses a different format, perhaps with more precision than a Java float, the Java Virtual Machine must convert the hardware format to and from the nearest IEEE-754 float value, perhaps with some loss of precision.
But what about temp. It takes extra time to convert from your hardware's format to IEEE-754 format so it makes sense to just use the hardware-format result of a/b in the temp/c operation. In addition, format conversions of intermediate results would likely lose some precision, making the final answer less precise. So Java normally leaves intermediate floating point results in local hardware format.
The problem is that different computers have different hardware floating point formats, so intermediate results are different and the final results are different. This violates the Java basic rule of machine independence.
With strictfp, every intermediate result is converted back into IEEE-754 format, then back into local hardware format for the next operation. This takes more time and costs some precision in the answer, but it results in every computer giving the same result running the same program with the same data.
SCJP 1.4, SCWCD in process
Joined: Dec 31, 2004
Thanks four your extraordinaryly well documented answer, Mike. That's exactly the answer I was looking for. I guess now I understand what this of strictfp is all about. I have read a lot in the JLS and JVMS, but I could not find there the simplicity and yet the profoundness of your reply.