Can float be round tripped via double without losing precision?

白昼怎懂夜的黑 提交于 2019-12-10 14:16:28

问题


If I have a C# float, can I convert it to double without losing any precision?

If that double were converted back to float, would it have exactly the same value?


回答1:


Yes. IEEE754 floating point (which is what C# must use) guarantees this:

  1. Converting a float to a double preserves exactly the same value

  2. Converting that double back to a float recovers exactly that original float.

The set of doubles is a superset of floats.

Note that this also applies to NaN, +Infinity, and -Infinity. The signedness of zero is also preserved.




回答2:


Let's test this with code:

[Fact]
public void IsFloatRoundTrippableToDouble()
{
    var bits = default(FloatUnion);
    bits.FloatData = float.MinValue;

    var testBits = default(FloatUnion);

    // ReSharper disable once LoopVariableIsNeverChangedInsideLoop
    while (bits.FloatData <= float.MaxValue)
    {
        var d = (double)bits.FloatData;
        testBits.FloatData = (float)d;

        if (bits.IntData != testBits.IntData)
            Assert.True(false);

        bits.IntData -= 1;
    }
}

[StructLayout(LayoutKind.Explicit)]
private struct FloatUnion
{
    [FieldOffset(0)] public uint IntData;
    [FieldOffset(0)] public float FloatData;
}

This code tests every float value between MinValue and MaxValue (except NaN, infinities, etc...). The in-memory byte representation is compared to ensure no other conversions take place.

Though it might seem crazy to test the ~4 billion possible floating point numbers, it actually runs in around 11 seconds on my machine.

And yes, the conversion is safe. Converting from float, to double, then back again doesn't lose any information.



来源:https://stackoverflow.com/questions/40550861/can-float-be-round-tripped-via-double-without-losing-precision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!