Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 270
jvn91173 Avatar asked Aug 03 '19 20:08

jvn91173


People also ask

What is strictfp modifier?

strictfp is an obsolete and unused reserved word in the Java programming language. Previously, this keyword was used as a modifier that restricted floating-point calculations to IEEE 754 semantics in order to ensure portability.

What does strictfp mean in class declaration in Java?

strictfp is used to ensure that floating points operations give the same result on any platform. As floating points precision may vary from one platform to another. strictfp keyword ensures the consistency across the platforms.

What does strictfp keyword mean in Java?

java. | strictfp is a keyword in java used for restricting floating-point calculations and ensuring same result on every platform while performing operations in the floating-point variable.


1 Answers

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.

like image 184
chrylis -cautiouslyoptimistic- Avatar answered Sep 24 '22 01:09

chrylis -cautiouslyoptimistic-