Why are floating point numbers printed so differently?

后端 未结 5 1386
有刺的猬
有刺的猬 2020-11-27 23:10

It\'s kind of a common knowledge that (most) floating point numbers are not stored precisely (when IEEE-754 format is used). So one shouldn\'t do this:

0.3 -         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 23:16

    If we want this property

    • every two different float has a different printed representation

    Or an even stronger one useful for REPL

    • printed representation shall be re-interpreted unchanged

    Then I see 3 solutions for printing a float/double with base 2 internal representation into base 10

    1. print the EXACT representation.
    2. print enough decimal digits (with proper rounding)
    3. print the shortest decimal representation that can be reinterpreted unchanged

    Since in base two, the float number is an_integer * 2^an_exponent, its base 10 exact representation has a finite number of digits.
    Unfortunately, this can result in very long strings... For example 1.0e-10 is represented exactly as 1.0000000000000000364321973154977415791655470655996396089904010295867919921875e-10

    Solution 2 is easy, you use printf with 17 digits for IEEE-754 double...
    Drawback: it's not exact, nor the shortest! If you enter 0.1, you get 0.100000000000000006

    Solution 3 is the best one for REPL languages, if you enter 0.1, it prints 0.1
    Unfortunately it is not found in standard libraries (a shame).
    At least, Scheme, Python and recent Squeak/Pharo Smalltalk do it right, I think Java too.

提交回复
热议问题