MinGW GCC 4.9.1 and floating-point determinism

前端 未结 2 1765
不思量自难忘°
不思量自难忘° 2021-02-13 20:39

I wrote a small program to compute the Euclidean norm of a 3-coordinate vector. Here it is:

#include 
#include 
#include 

        
2条回答
  •  情歌与酒
    2021-02-13 21:02

    There is a difference in precision of a floating point number depending on where it is stored. If the compiler keeps one variable in a register, it has higher precision as a variable stored in memory. You can try to force your variables to be stored in memory before, like:

    int main()
    {
        std::array arr = { 4.0, -2.0, 6.0 };
        volatile double v1 = norm(arr);
        volatile double v2 = norm(arr);
        std::cout << v1 - v2 << '\n';
    }
    

    This gives you the expected result of 0.

提交回复
热议问题