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

前端 未结 7 1194
余生分开走
余生分开走 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:53

    In absolute terms, the smallest amount you can add to a floating point value to make a new distinct value will depend on the current magnitude of the value; it will be the type's machine epsilon multiplied by the current exponent.

    Check out the IEEE spec for floating point represenation. The simplest way would be to reinterpret the value as an integer type, add 1, then check (if you care) that you haven't flipped the sign or generated a NaN by examining the sign and exponent bits.

    Alternatively, you could use frexp to obtain the current mantissa and exponent, and hence calculate a value to add.

提交回复
热议问题