Exact textual representation of an IEEE “double”

后端 未结 4 1255
星月不相逢
星月不相逢 2021-01-12 14:35

I need to represent an IEEE 754-1985 double (64-bit) floating point number in a human-readable textual form, with the condition that the textual form can be parsed back into

4条回答
  •  生来不讨喜
    2021-01-12 15:09

    Sound like you want Burger's algorithm (PDF):

    In free-format mode the algorithm generates the shortest correctly rounded output string that converts to the same number when read back in regardless of how the reader breaks ties when rounding.

    Sample source code (in C and Scheme) is available as well.

    This is the algorithm used in Python 3.x to ensure floats can be converted to strings and back without any loss of accuracy. In Python 2.x, floats were always represented with 17 significant digits because:

    repr(float) produces 17 significant digits because it turns out that’s enough (on most machines) so that eval(repr(x)) == x exactly for all finite floats x, but rounding to 16 digits is not enough to make that true. (Source: http://docs.python.org/tutorial/floatingpoint.html)

提交回复
热议问题