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

后端 未结 4 1590
[愿得一人]
[愿得一人] 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

    Once you get past the number of digits contained in a double, you're at the mercy of your compiler's library implementation. Different algorithms for converting from binary to decimal will result in different output. Neither can be more accurate than the other.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-12 20:57

    I think you have installed g++ 32 bit version on windows, and 64 bit on linux. Just verify the program you are running, if it's 32 or 64 bit (you can check it by watching in task manager)

    0 讨论(0)
  • 2021-01-12 21:14

    The Wikipedia entry on double precision defines the bounding errors for translation between decimal digits and double values very succinctly:

    This gives from 15 - 17 significant decimal digits precision. If a decimal string with at most 15 significant decimal is converted to IEEE 754 double precision and then converted back to the same number of significant decimal, then the final string should match the original; and if an IEEE 754 double precision is converted to a decimal string with at least 17 significant decimal and then converted back to double, then the final number must match the original.

    0 讨论(0)
提交回复
热议问题