How can floating point calculations be made deterministic?

后端 未结 6 749
执念已碎
执念已碎 2020-12-03 21:21

Floating point calculation is neither associative nor distributive on processors. So,

(a + b) + c is not equal to a + (b + c)

and <

6条回答
  •  萌比男神i
    2020-12-03 21:32

    Try storing each intermediate result in a volatile object:

    volatile double a_plus_b = a + b;
    volatile double a_plus_b_plus_c = a_plus_b + c;
    

    This is likely to have nasty effects on performance. I suggest measuring both versions.

    EDIT: The purpose of volatile is to inhibit optimizations that might affect the results even in a single-threaded environment, such as changing the order of operations or storing intermediate results in wider registers. It doesn't address multi-threading issues.

    EDIT2: Something else to consider is that

    A floating expression may be contracted, that is, evaluated as though it were an atomic operation, thereby omitting rounding errors implied by the source code and the expression evaluation method.

    This can be inhibited by using

    #include 
    ...
    #pragma STDC FP_CONTRACT off
    

    Reference: C99 standard (large PDF), sections 7.12.2 and 6.5 paragraph 8. This is C99-specific; some compilers might not support it.

提交回复
热议问题