How to alter a float by its smallest increment (or close to it)?

前端 未结 7 1203
余生分开走
余生分开走 2020-11-30 02:05

I have a double value f and would like a way to nudge it very slightly larger (or smaller) to get a new value that will be as close as possible to

7条回答
  •  旧巷少年郎
    2020-11-30 02:40

    u64 &x = *(u64*)(&f);
    x++;
    

    Yes, seriously.

    Edit: As someone pointed out, this does not deal with -ve numbers, Inf, Nan or overflow properly. A safer version of the above is

    u64 &x = *(u64*)(&f);
    if( ((x>>52) & 2047) != 2047 )    //if exponent is all 1's then f is a nan or inf.
    {
        x += f>0 ? 1 : -1;
    }
    

提交回复
热议问题