Floating point constants are of type double by default in C ++. Since a long double more accurate than a double , you can lose significant digits when the constants of long double converted to double . To handle these constants, you need to use the L suffix to maintain long double precision. For example,
long double x = 8.99999999999999999; long double y = 8.99999999999999999L; std::cout.precision(100); std::cout << "x=" << x << "\n"; std::cout << "y=" << y << "\n";
The output for this code is on my system, where double is 64 bits and long double 96, is
x=9 y=8.9999999999999999895916591441391574335284531116485595703125
What happens is that x rounded to the destination, because the constant is implicitly converted to double , and 8.99999999999999999 not represented as a 64-bit floating point number. (Note that the representation as a long double also not completely accurate. All digits after the first line of 9 are attempts to approximate the decimal number 8.99999999999999999 as close as possible using 96 binary bits.)
In your example, there is no need for the constant L , since 3.0 is represented exactly as either double or long double . The value of the double constant is implicitly converted to long double without loss of precision.
The case with F not so obvious. This can help with overload, as Zan Links points out. I'm not sure, but it can also avoid some subtle rounding errors (i.e., it is possible that encoding as float will give a different result from encoding as double , and then rounding to float ).
Chris Conway Sep 04 '09 at 23:13 2009-09-04 23:13
source share