Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/134.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 比较32位浮点和64位浮点的移植代码,这个值代表什么?_C++_Floating Point_Floating Point Precision - Fatal编程技术网

C++ 比较32位浮点和64位浮点的移植代码,这个值代表什么?

C++ 比较32位浮点和64位浮点的移植代码,这个值代表什么?,c++,floating-point,floating-point-precision,C++,Floating Point,Floating Point Precision,我移植了一些比较浮点数以处理64位双精度而不是32位浮点数的代码,但我对代码中使用的一些神奇数字有点困惑 资料来源: 代码如下: bool AlmostEqual2sComplement(float A, float B, int maxUlps) { // Make sure maxUlps is non-negative and small enough that the // default NAN won't compare as equal to anything.

我移植了一些比较浮点数以处理64位双精度而不是32位浮点数的代码,但我对代码中使用的一些神奇数字有点困惑

资料来源:

代码如下:

bool AlmostEqual2sComplement(float A, float B, int maxUlps)
{
    // Make sure maxUlps is non-negative and small enough that the
    // default NAN won't compare as equal to anything.
    assert(maxUlps > 0 && maxUlps < 4 * 1024 * 1024);
    int aInt = *(int*)&A;
    // Make aInt lexicographically ordered as a twos-complement int
    if (aInt < 0)
        aInt = 0x80000000 - aInt;
    // Make bInt lexicographically ordered as a twos-complement int
    int bInt = *(int*)&B;
    if (bInt < 0)
        bInt = 0x80000000 - bInt;
    int intDiff = abs(aInt - bInt);
    if (intDiff <= maxUlps)
        return true;
    return false;
}
bool almostequal2Scomplete(浮点A、浮点B、整数最大值)
{
//确保maxUlps为非负且足够小,以便
//默认NAN不会与任何内容进行比较。
断言(maxUlps>0&&maxUlps<4*1024*1024);
int ANT=*(int*)&A;
//使aInt按字典顺序排列为两个补码int
if(aInt<0)
AIT=0x8000000-AIT;
//使bInt按字典顺序排列为两个补码int
int bInt=*(int*)&B;
if(bInt<0)
bInt=0x8000000-bInt;
int intDiff=abs(aInt-bInt);
如果(intDiffeww)

4*1024*1024是22位,这比浮点的显式尾数位数少一位。我认为double的等效值是2**51

关于0x800,您是对的……这段代码依赖于这样一个事实:IEEE浮点数可以进行比较,就好像它们是用符号和大小表示的整数一样


当然,这个代码充满了未定义的行为,更不用说讨厌、粗野和短小了。< /P> <代码> 2 **==0x800亿×< /代码>?我也不是一个大的C++迷,我把它移植到D,在这里,这个未定义的行为胡说不存在。Dunno,在第7次0后丢失了计数。即使您修复了尾端并要求IEEE754,将
double
重新解释为
int
也是个坏消息。我不会将double重新解释为int。是的,您是-这就是
*(int*)&a
所做的,以及整个函数所依赖的。(假设您已将float更改为您所说的双倍。)