Reputation: 4574
My application must produce exactly the same numeric results on all machines. I understand that float/double math in C# is not deterministic, but how about the binary representation of literal values?
float x = 1.23f;
How will 1.23f
be stored in the compiled DLL file? As a binary representation of 32-bit IEEE-754 format float? Or as some intermediate representation that will need converting to IEEE-754 floating point by the jitter on target machine (a potential source of indeterminism)?
I understand why floating point operations in C# are not deterministic. I am asking ONLY whether the binary representation of literals is deterministic. Please, no answers about floating point determinism in general.
Upvotes: 1
Views: 168
Reputation: 109587
They are stored as IEEE 754 format.
You can verify this by using ILDASM.EXE to disassemble the generated code and inspecting the binary values.
For example, float x = 1.23f;
will generate:
IL_0000: /* 22 | A4709D3F */ ldc.r4 1.23
(Note that this is stored in little-endian format on Intel platforms.)
Upvotes: 2
Reputation: 147
The decimal type was introduced for this reason. Check it out in the official microsoft documentation here. https://learn.microsoft.com/en-us/dotnet/api/system.decimal?view=netframework-4.8
A decimal number is a floating-point value that consists of a sign, a numeric value where each digit in the value ranges from 0 to 9, and a scaling factor that indicates the position of a floating decimal point that separates the integral and fractional parts of the numeric value.
The binary representation of a Decimal value consists of a 1-bit sign, a 96-bit integer number, and a scaling factor used to divide the 96-bit integer and specify what portion of it is a decimal fraction. The scaling factor is implicitly the number 10, raised to an exponent ranging from 0 to 28. Therefore, the binary representation of a Decimal value the form, ((-296 to 296) / 10(0 to 28)), where -(296-1) is equal to MinValue, and 296-1 is equal to MaxValue. For more information about the binary representation of Decimal values and an example, see the Decimal(Int32[]) constructor and the GetBits method.
The scaling factor also preserves any trailing zeros in a Decimal number. Trailing zeros do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeros might be revealed by the ToString method if an appropriate format string is applied.
Upvotes: -1