Search code examples
c++floating-pointieee-754

process of mapping a floating point literal to its binary representation


Consider the exact float values around 0.3

1) 0.2999999523162841796875
2) 0.2999999821186065673828125
3) 0.300000011920928955078125
4) 0.3000000417232513427734375
5) 0.30000007152557373046875

When we write the following code in C++

auto x = 0.30f

compiler has to parse the 0.30f token and make x of type float with value 0.300000011920928955078125. (option 3 above)

I am curious how compilers reach that value, and not the values around it. One theory is that they call strtof function to get the float. Here is implementation of strtof (it is basically going through each character of the string, multiplying by a power of 10 and figuring out the location of decimal). It is not obvious to me why this method will give option 3 and not option 4 or 5.


Solution

  • One theory is that they call strtof function to get the float.

    Indeed; they use a function comparable to strtof. There are open source compilers. You can look at how they parse literals. Here is an implementation from GCC. It is too big to copy here. It uses GNU MPFR (multiple-precision floating-point) library.

    The IEEE-754 document specifies how this conversion must behave on IEEE-754 conforming systems in the section titled 5.12 Details of conversion between floating-point data and external character sequences. Besides conversion functions, it also applies to translation time conversions such as those of floating point literals.