Is VC ++ using fp: fast causing incorrect (not just inaccurate) results - is this a compiler error?

I installed the latest VS2017 update (15.4.4), and when compiling our projects, the initial tests started with an error. It seems that the problem occurs in some scenarios when using optimizations (/ O2) and a fast floating point model (/ fp: fast). This problem did not happen with the previous compiler (VS2017 update 15.2).

Here is an example program:

#include <iostream>

const float FACTOR = 0.01745329251994329576923690768489f;

unsigned long long hoursToMicrosecs(int hours)
{
    return hours * 3600 * 1000000LL;
}

float degToRad(float deg)
{
    return deg * FACTOR;
}

float f(int u1, int u2)
{
    float percent = ((u1 - u2) / 1000.0f) / (hoursToMicrosecs(24) / 1000000.0f);
    return degToRad(percent * 360);
}

int main()
{   
    auto result = f(3600000, 35063681);
    std::cout << result << '\n';
    return (result > -3.0f) ? 0 : -1;
}

result should be -2.2881, but the output is actually -394.868, which is not just inaccurate.

It works if I do one of the following:

  • Remove Optimization
  • Change to fp: exact
  • Return to the previous compiler (15.2)

, - - .

- :

011F1000  vmovss      xmm0,dword ptr [__real@c3c56f11 (011F2118h)]  

: ( ), fp: fast?

+6
1

. , : hoursToMicroseconds(24) . , unsigned long long 1000000LL. unsigned int, 500654080, 86400000000. , -394.868.

, . , , unsigned long long double.

, ? constexpr, result constexpr main(), . , , -, , , .

+5
source

All Articles