How to calculate the number of significant decimal digits of a c++ double?

六眼飞鱼酱① 提交于 2019-11-30 13:46:28

I think you are talking about how to print the minimum number of floating point digits that allow you to read the exact same floating point number back. This paper is a good introduction to this tricky problem.

http://grouper.ieee.org/groups/754/email/pdfq3pavhBfih.pdf

The dtoa function looks like David Gay's work, you can find the source here http://www.netlib.org/fp/dtoa.c (although this is C not Java).

Gay also wrote a paper about his method. I don't have a link but it's referenced in the above paper so you can probably google it.

You can use the ios_base::precision technique where you can specify the number of digits you want

For example

#include <iostream>
using namespace std;

int main () {
double f = 3.14159;
cout.unsetf(ios::floatfield);            // floatfield not set
cout.precision(5);
cout << f << endl;
cout.precision(10);
cout << f << endl;
cout.setf(ios::fixed,ios::floatfield);   // floatfield set to fixed
cout << f << endl;
return 0;

The above code with output
3.1416
3.14159
3.1415900000

There is a utility called numeric_limits:

#include <limits>

    ...
    int num10 = std::numeric_limits<double>::digits10;
    int max_num10 = std::numeric_limits<double>::max_digits10;

Note that IEEE numbers are not represented exactly bydecimal digits. These are binary quantities. A more accurate number is the number of binary bits:

    int bits = std::numeric_limits<double>::digits;

To pretty print all the significant digits use setprecision with this:

out.setprecision(std::numeric_limits<double>::digits10);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!