As we know, IEEE floating point numbers can store exact representations of all integers and integer multiples of inverses-of-powers-of-two such as 1/2 or 3/4, as long the numbers keep within the range of the floating-point type.
However, do floating-point parsers generally guarantee exact results of parsing decimal representations of such numbers?
For instance, if I use 0.75 as a double literal in a C program, will the compiler guarantee that the compiled code contains the exact representation of 3/4, or is there a risk that it will produce the sum of some inexact representation of 0.7 and some inexact representation of 0.05?
Or, likewise, if I use 3e4 as a double literal, might the exact 3 be multiplied by some inexact representation of 2^(4*ln(10)/ln(2)) or some similar math?
Are there any standards that FP-parsers are generally required to follow in this matter, or is it generally left entirely to the implementation? If it is the latter, does anyone know how practically important implementations like GCC or glibc actually work?
I’m mostly just asking for curiosity and not because I want to rely on the behavior; but it might, at times, be quite convenient to know that FP equality comparisons are guaranteed to work if the values can be known to only come from literal sources.
The C standard permits a floating-point constant to be either the representable value nearest to the exact value of the literal constants or the larger or smaller representable value immediately adjacent to the nearest value, per C 2011 6.4.4.2 3. Some C implementations do better. Modern implementations should do better, as there are published algorithms for doing the conversion correctly.
However, the C standard also provides for hexadecimal floating-point constants, which make it easy for a compiler to do the conversion correctly. A hexadecimal floating-point constant has the basic form 0xhhh.hhhpeee, where hhh are hexadecimal digits and eee is a decimal exponent, which may have a sign. (The hexadecimal digits on one side of the “.” may be omitted if they are zero, and the period may be omitted if the digits on the right are omitted.) The exponent is for a power of two.
The C standard requires that a hexadecimal floating-point constant be correctly rounded if the radix for floating-point numbers is a power of 2 in the C implementation. It recommends that a diagnostic message be produced if the hexadecimal constant cannot be represented exactly.
E.g.,
0x3p-2should be exactly .75.