A fast method to round a double to a 32-bit int explained

前端 未结 3 1509
谎友^
谎友^ 2020-11-28 17:18

When reading Lua\'s source code, I noticed that Lua uses a macro to round a double to a 32-bit int. I extracted the macro

3条回答
  •  渐次进展
    2020-11-28 18:06

    Here is a simpler implementation of the above Lua trick:

    /**
     * Round to the nearest integer.
     * for tie-breaks: round half to even (bankers' rounding)
     * Only works for inputs in the range: [-2^51, 2^51]
     */
    inline double rint(double d)
    {
        double x = 6755399441055744.0;  // 2^51 + 2^52
        return d + x - x;
    }
    

    The trick works for numbers with absolute value < 2 ^ 51.

    This is a little program to test it: ideone.com

    #include 
    
    int main()
    {
        // round to nearest integer
        printf("%.1f, %.1f\n", rint(-12345678.3), rint(-12345678.9));
    
        // test tie-breaking rule
        printf("%.1f, %.1f, %.1f, %.1f\n", rint(-24.5), rint(-23.5), rint(23.5), rint(24.5));      
        return 0;
    }
    
    // output:
    // -12345678.0, -12345679.0
    // -24.0, -24.0, 24.0, 24.0
    

提交回复
热议问题