Floating point numbers and their Java representation - part 3

Strict floating point precision

Java supports two types of decimal number representations - Single-precision floating-point format or 32 bit float and Double-precision floating-point format or 64 bit double format. Both these formats are IEEE 754 compliant and produes predictable results for mathematical expressions involving them

Since Java 1.2, while evaluating an expression involving floats and doubles, the intermediate results are not necessarily stored in standard IEEE format but are stored in a higher precision format to avoid underflows or overflows ( The final result was however downgraded to fit to IEEE 32or 64 bit format)

From the VM perspective, turning on this higher precision means the following:

Precision
Intermediate
32 bits
64 bits
64 bits
80 bits (if available)

Now not every system supports 80 bit precision. That means the same calculation done in one machine can use 80 bit precision while on another machine it will be limited to 64 bit precision. So, there's a chance that the same calculation performed in different machines can produce different results

For many applications, though, the need is to have consistent results across platforms even at the cost of using a lower precision. In such cases strictfp keyword can be used. Strictfp keyword ensures that
there wont be any intermediary result stored in a higher precision

Strictfp keyword can be used :
1. with a method
makes all float or double expressions within the method body to be strictly IEEE 754 32/64 bit format compliant
2. with an interface
makes all float or double expressions within the interface declaration be explicitly and strictly IEEE 754 32/64 bit compliant
3. with a class
makes all float or double expressions within the class declaration (including within variable initializers, instance initializers, static initializers, and constructors) strictly IEEE 754 32/64 bit compliant

comments powered by Disqus