x*x != x*x 在自变量中

x*x != x*x in auto-variable?

本文关键字:自变量      更新时间:2023-10-16
如何将

x * x存储在" auto变量"中来更改?我认为它应该仍然是一样的,我的测试表明类型、大小和值显然都是相同的

但即使x * x == (xx = x * x)也是错误的。管他呢?

(注意:我知道IEEE 754以及浮动和双重工作原理以及它们的常见问题,但这个让我感到困惑。

#include <iostream>
#include <cmath>
#include <typeinfo>
#include <iomanip>
using namespace std;
int main() {
    auto x = sqrt(11);
    auto xx = x * x;
    cout << boolalpha << fixed << setprecision(130);
    cout << "   xx == 11           " << (   xx == 11          ) << endl;
    cout << "x * x == 11           " << (x * x == 11          ) << endl;
    cout << "x * x == xx           " << (x * x == xx          ) << endl;
    cout << "x * x == (xx = x * x) " << (x * x == (xx = x * x)) << endl;
    cout << "x * x == x * x        " << (x * x == x * x       ) << endl;
    cout << "types        " << typeid(xx).name() << " " << typeid(x * x).name() << endl;
    cout << "sizeofs      " << sizeof(xx) << " " << sizeof(x * x) << endl;
    cout << "xx           " << xx    << endl;
    cout << "x * x        " << x * x << endl;
}

下面是输出:

   xx == 11           true
x * x == 11           false
x * x == xx           false
x * x == (xx = x * x) false
x * x == x * x        true
types        d d
sizeofs      8 8
xx           11.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
x * x        11.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

编译如下:

C:Stefancodeleetcode>g++ test4.cpp -static-libstdc++ -std=c++11 -o a.exe
C:Stefancodeleetcode>g++ --version
g++ (GCC) 4.8.1
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

这是双精度的常见不精确性。 您没有提到您的硬件,但在 x86(32 位英特尔)上,计算期间使用的临时值是 10 字节长的双精度值。 x * x将是其中之一,而xx = x * x将存储为 8 字节双精度,然后再加载回 FPU 进行比较。

如果打开优化或生成 64 位可执行文件,则可能会得到不同的结果。