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 位可执行文件,则可能会得到不同的结果。
相关文章:
- 以代数表达式中的数字和单位作为自变量的文字
- 为什么相对于右值引用参数,右值引用自变量更喜欢常量左值引用
- 关于链表,这两种方法有什么不同?C++中的1个自变量与2个自变量
- C++方法内每个对象的自变量
- 在C++中,如何将相同的操作应用于一组自变量
- x*x != x*x 在自变量中
- 如果指针是函数自变量并且通过引用传递值,我应该删除它吗
- 将2D数组作为自变量传递给采用1D数组的函数
- 作为自变量的右值引用和左值引用之间的差异
- 特征向量4d作为函数自变量
- 我们如何计算旋转和平移两个立体相机在opencv StereoRectify(r,t自变量)中使用
- 一个函数可以接收两个自变量吗?每个自变量来自两个不同的函数
- 为什么volatile局部变量的优化与volatile自变量不同,以及为什么优化器会从后者生成无操作循环
- _stdcall、C++/内联ASM中的变量自变量