Search code examples
javafloating-pointstrictfp

Does Java's strictfp modifier apply through function calls?


More precisely, if there exists a function in the call stack with the strictfp modifier, will the function at the top of the call stack also adhere to the strictfp specifier?

public class Main {

    // case 1: strictfp not present at top of call stack
    private static double bar1(double x) {
        return Math.sin(x);
    }

    strictfp private static double foo1(double x) {
        return bar1(x);
    }

    // case 2: strictfp present at top of call stack
    strictfp private static double bar2(double x) {
        return Math.sin(x);
    }

    strictfp private static double foo2(double x) {
        return bar2(x);
    }

    public static void main(String[] args) {
        double x = 10.0;
        System.out.println(foo1(x)); // -0.5440211108893698
        System.out.println(foo2(x)); // -0.5440211108893698
    }
}

In this example, foo1 and foo2 appear to return the same value. In other words, it doesn't look like it matters whether the function at the top of the call stack has the strictfp modifier when a function further down also has the modifier.

Does this always hold true? What if I choose differing values for x? What if I choose floating point operations other than sine?


Solution

  • JLS 15.4:

    If an expression is not a constant expression, then consider all the class declarations, interface declarations, and method declarations that contain the expression. If any such declaration bears the strictfp modifier (§8.1.1.3, §8.4.3.5, §9.1.1.2), then the expression is FP-strict.

    [...]

    It follows that an expression is not FP-strict if and only if it is not a constant expression and it does not appear within any declaration that has the strictfp modifier.

    Therefore, calls to external methods or other ways of obtaining a floating-point expression do not "inherit" the FP-strictness of something up the call stack.