Search code examples
javafloating-pointfloating-accuracy

Java parsefloat same result on every CPU


I just read about strictfp (https://en.wikipedia.org/wiki/Strictfp) and the fact that floating / double point operations may yield different results on different CPUs since Java 1.2.

Now I wonder if the same is true for Float.valueOf method? I cannot find any source to this. The javadoc for valueOf explicitly states that:

Note that the round-to-nearest rule also implies overflow and underflow behaviour;

Which to me indicates that it may be different if strictfp is turned off.

Is there a source that is exact on this topic and states that this is the case or not?


Solution

  • Which to me indicates that it may be different if strictfp is turned off.

    The JLS says that the meaning of the strictfp modifier is that any expressions within the class or method are evaluated as FP-strict.

    However, JLS doesn't say that if you call a different method in an FP-strict expressions that the calculations in that method are automatically FP-strict as well.

    This means that the result you get from a call to Float.valueOf doesn't depend on strictfp / the FP-strictness of the caller.

    The flipside is that the (internal) Java class that does the conversion in Float.valueOf(String):

    • takes care to use specific values for INF and NaN values,
    • takes care to ensure that the value is within the error bounds set out in the javadoc, and
    • in the Float case, it does the conversion in double arithmetic.

    However, the conversion method is not a strictfp method, so if the code was sensitive to FP-strictness, then there would be a problem.

    The class to look for is jdk.internal.math.FloatingDecimal in Java 11.