-->

c++ exp function different results under x64 on i7

2019-08-09 17:12发布

问题:

When I execute a simple x64 application with the following code, I get different results on Windows PCs with a i7-3770 and i7-4790 CPU.

#include <cmath>
#include <iostream>
#include <limits>

void main()
{
  double val = exp(-10.240990982718174);
  std::cout.precision(std::numeric_limits<double>::max_digits10);
  std::cout << val;
}

Result on i7-3770:

3.5677476354876406e-05

Result on i7-4790:

3.5677476354876413e-05

When I modify the code to call

unsigned int control_word;
_controlfp_s(&control_word, _RC_UP, MCW_RC);

before the exp function call, both CPUs deliver the same results.

My questions:

  • Does anyone have an idea for the reason of the differences between the i7-3770 and i7-4790?
  • Is there a way to set the floating point precision or consistency in a Visual Studio 2015/2017 C++ project for the whole project and not only for the following function call? The "Floating Point Model" setting (/fp) does not have any influence on the results here.

回答1:

Assuming that double is coded using IEEE-754, and using this decimal to binary converter, you can see that:

3.5677476354876406e-05 is represented in hexa as 0x3F02B48CC0D0ABA8 3.5677476354876413e-05 is represented in hexa as 0x3F02B48CC0D0ABA9

which differ only in the last bit, probably due round error.



回答2:

I did some further investigations and I found out the following facts:

  • the problem does also occur on Windows with a different compiler (Intel)
  • on a linux system both values are equal

I also posted this question to the Visual Studio Community. I got the information, that Haswell and newer CPUs use FMA3. You can disable this feature with _set_FMA3_enable(0) at the beginning of the program. When I do this, the results are the same.