Is it possible to swim around with a double without losing accuracy?

If I have C # float , is it possible to convert it to double without loss of precision?

If this double was converted back to float , will it have exactly the same value?

+5
source share
2 answers

Yes. The IEEE754 floating point (which should use C #) guarantees the following:

  • Converting a float to double keeps exactly the same value

  • Converting this double back to float restores exactly this original float .

The double set is a superset of float s.

Note that this also applies to NaN , +Infinity and -Infinity . Zero subscription is also preserved.

+8
source

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 checks each float value between MinValue and MaxValue (except NaN , infinity, etc.). The representation of bytes in memory is compared to ensure that no other conversions occur.

Although it might seem crazy to test the number of possible ~ 4 billion floating point numbers, it actually works for about 11 seconds on my machine.

And yes, the conversion is safe. Converting from float, double, and then back will not lose any information.

+6
source

Source: https://habr.com/ru/post/1259595/


All Articles