重新审视浮点数精度:九位浮点数的可移植性

  • Summary: Last year showed float vars can be converted to/from text. Tested if floats converted by one compiler and restored by another would be faithful. VC++ gets last digit wrong 4 times across 2B positive floats, has 6,694,304 legitimate disagreements with g++ 6. Dev 14 rewrote float printing routines. This is part of a 2012 floating-point series. Crucial distinction between digits to uniquely identify and exactly print float. ASCII non-equivalence due to rounding rules (VC++ rounds up for ties, g++ uses round-to-nearest-even). Double rounding issue in VC++ (prints 17 digits and rounds). But differences are small (less than 1/100,000,000 from actual float value), and scanf recovers original value. Debuggers: VS 2010 watch window shows 8 digits, VS 2012 and gdb show 9. Using %1.8ef to print floats is reliable. Other resources: [article on gcc/VC++ differences], [How to Print Floating-Point Numbers Accurately], [Incorrect Round-Trip Conversions in Visual C++].
  • Key Information:

    • VC++ and g++ have differences in printing floats, especially in rounding.
    • Discrepancies are usually small and don't prevent round-tripping.
    • Debuggers show different digit counts for floats.
    • Using %1.8ef for printing floats is reliable.
  • Important Details:

    • VC++ prints exponents as 3-digit numbers, g++ as 2-digit.
    • In 6,694,304 cases, difference is due to printing policy.
    • In 4 cases, VC++ double rounds.
    • VS 2010 watch window shows 8 digits, VS 2012 and gdb show 9.
    • Reading floats back with scanf works.
阅读 17
0 条评论