Double multiplication differs between compile time and runtime in 32 bit platform

前端 未结 3 1975
太阳男子
太阳男子 2021-02-12 18:00

I\'m compiling and running the following program in 32 and 64 bit platforms:

int main()
{
  double y = 8.34214e08;
  double z = 1.25823e45;

  return y * z == 8.         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-12 18:37

    IEEE-754 allows intermediate computations to be done in a greater precision (emphasis mine).

    (IEEE-754:2008) "A language standard should also define, and require implementations to provide, attributes that allow and disallow value-changing optimizations, separately or collectively, for a block. These optimizations might include, but are not limited to: [...] Use of wider intermediate results in expression evaluation."

    In your case for example on a IA-32, the double values could be stored in the x87 FPU registers with greater precision (80-bit instead of 64). So you are actually comparing a multiplication done on double precision with a multiplication done on double-extended precision.

    For example, on x64 where the result is 1 (the x87 FPU is not used as SSE is used instead), adding gcc option -mfpmath=387 to use the x87 makes the result change to 0 on my machine.

    And if you wonder if that is also allowed by C, it is:

    (C99, 6.3.1.p8) "The values of floating operands and of the results of floating expressions may be represented in greater precision and range than that required by the type;"

提交回复
热议问题