Number of precision digits for double in C++ different in windows and Linux. Why? Linux shows more than 20 non-zero precision digits

后端 未结 4 1633
[愿得一人]
[愿得一人] 2021-01-12 20:24

Just did this:

double val1=numeric_limits::max();
cout.precision(70);
cout<<\"\\nVal1: \"<

In Windows I sta

4条回答
  •  梦谈多话
    2021-01-12 20:50

    When you print out a double, you often have to print out many, many digits before you print out the exact value of the double. It is possible to print out a double exactly. For example, the double closest to 1/3 has the value:

    0.333333333333333314829616256247390992939472198486328125
    

    Printing out this value exactly requires 54 digits past the decimal point. But people say a double only has about 16 digits of precision. What gives?

    When you say that a double has 16 digits of precision, that means that you need at least 16 digits to make the double survive a round trip. That is, the following process preserves the input data:

    double -> 16 digit decimal -> double
    

    So the extra digits past 16 aren't necessarily garbage, they're just unnecessary. And according to the standard, they can be almost anything -- as long as reading the result will give you the same double back.

    The Summary: My guess is that your standard library on Linux is printing out the exact value of the double, and the Windows library is truncating the result. Both actions are permitted by the standard.

    You almost certainly don't need the exact value of a double anyway, since arithmetic on floating point numbers is usually inexact.

提交回复
热议问题