IEE 754 total order in standard C++11

后端 未结 1 759
轻奢々
轻奢々 2021-02-20 10:27

According to the IEEE floating point wikipage (on IEEE 754), there is a total order on double-precision floating points (i.e. on C++11 implementations having IEEE-754 floats, li

1条回答
  •  天命终不由人
    2021-02-20 10:53

    I would use:

    int totalcompare(double x, double y) {
        int64_t rx, ry;
    
        memcpy(&rx, &x, sizeof rx);
        memcpy(&ry, &y, sizeof ry);
    
        if (rx == ry) return 0;
    
        if (rx < 0) rx ^= INT64_MAX;
        if (ry < 0) ry ^= INT64_MAX;
    
        if (rx < ry) return -1; else return 1;
     }
    

    This makes 0.0 and -0.0 compare unequal, whereas if (x==y) return 0; in your version makes them compare equal, meaning that your version is only a preorder. NaN values are above the rest and different NaNs compare different. All values comparable for <= should be in the same order for the above relation.

    Note: the above function is C. I do not know C++.

    0 讨论(0)
提交回复
热议问题