Calculate the unit in the last place (ULP) for doubles

后端 未结 2 1237
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 00:16

Does .NET have a built-in method to calculate the ULP of a given double or float?

If not, what is the most efficient way to do so?

2条回答
  •  借酒劲吻你
    2020-12-02 00:40

    It seems the function is pretty trivial; this is based on the pseudocode in the accepted answer to the question linked by vulkanino:

    double value = whatever;
    long bits = BitConverter.DoubleToInt64Bits(value);
    double nextValue = BitConverter.Int64BitsToDouble(bits + 1);
    double result = nextValue - value;
    

    For floats, you'd need to provide your own implementation of SingleToInt32Bits and Int32BitsToSingle, since BitConverter doesn't have those functions.

    This page shows the special cases in the java implementation of the function; handling those should be fairly trivial, too.

提交回复
热议问题