How to find nearest next/previous double value (numeric_limits::epsilon for given number)

后端 未结 4 1584
花落未央
花落未央 2020-12-14 19:07

The title is quite self-explanatory, input is given double value, and I want to add/substract the smallest amount possible.

4条回答
  •  情话喂你
    2020-12-14 19:43

    Here's a very dirty trick that isn't actually legal and only works if your platform uses IEEE754 floats: The binary representation of the float is ordered in the same way as the float value, so you can increment the binary representation:

    double x = 1.25;
    
    uint64_t * const p = reinterpret_cast(&x);
    
    ++*p;   // undefined behaviour! but it gets the next value
    
    // now x has the next value
    

    You can achieve the same effect entirely legally by doing the usual binary copy gymnastics to obtain a proper uint64_t value. Make sure to check for zero, infinity and NaN properly, too.

提交回复
热议问题