How do you print the EXACT value of a floating point number?

后端 未结 10 1274
自闭症患者
自闭症患者 2020-11-27 03:45

First of all, this is not a floating point newbie question. I know results of floating point arithmetic (not to mention transcendental functions) usually cannot be represent

10条回答
  •  一整个雨季
    2020-11-27 04:28

    Although it's C# and your question is tagged with C, Jon Skeet has code to convert a double to its exact representation as a string: http://www.yoda.arachsys.com/csharp/DoubleConverter.cs

    From a quick glance, it does not appear to be too hard to port to C, and even easier to write in C++.

    Upon further reflection, it appears that Jon's algorithm is also O(e^2), as it also loops over the exponent. However, that means the algorithm is O(log(n)^2) (where n is the floating-point number), and I'm not sure you can convert from base 2 to base 10 in better than log-squared time.

提交回复
热议问题