I am currently working on a C ++ project that performs numerical calculations. The vast, vast majority of code uses single precision floating point values and works great with this. Because of this, I use compiler flags to make basic floating point literature single precision instead of double precision, which is the default. I find this easier to read, and I don’t have to worry about forgetting the “f” somewhere. However, from time to time I need the extra precision offered by double precision calculations, and my question is how can I get a double precision literal in such an expression. Each path I've tried so far first saves the value in one precision variable and converts the truncated value to a double precision value. Not what I want.
Some methods I've tried so far are listed below.
#include <iostream> int main() { std::cout << sizeof(1.0E200) << std::endl; std::cout << 1.0E200 << std::endl; std::cout << sizeof(1.0E200L) << std::endl; std::cout << 1.0E200L << std::endl; std::cout << sizeof(double(1.0E200)) << std::endl; std::cout << double(1.0E200) << std::endl; std::cout << sizeof(static_cast<double>(1.0E200)) << std::endl; std::cout << static_cast<double>(1.0E200) << std::endl; return 0; }
Running with single precision constants gives the following results.
~/path$ g++ test.cpp -fsingle-precision-constant && ./a.out test.cpp:6:3: warning: floating constant exceeds range of 'float' [-Woverflow] test.cpp:7:3: warning: floating constant exceeds range of 'float' [-Woverflow] test.cpp:12:3: warning: floating constant exceeds range of 'float' [-Woverflow] test.cpp:13:3: warning: floating constant exceeds range of 'float' [-Woverflow] test.cpp:15:3: warning: floating constant exceeds range of 'float' [-Woverflow] test.cpp:16:3: warning: floating constant exceeds range of 'float' [-Woverflow] 4 inf 16 1e+200 8 inf 8 inf
I understand that 8 bytes provided in the last two cases should be enough to hold 1.0E200, a theory supported by the next output, where the same program is compiled without -fsingle-precision-constant.
~/path$ g++ test.cpp && ./a.out 8 1e+200 16 1e+200 8 1e+200 8 1e+200
A possible workaround suggested by the above examples is to use even-numbered precision floating point literals, which I originally planned to use with double precision, and applying double precision when required by libraries and the like. However, this is a bit wasteful.
What else can I do?
c ++ gcc precision literals
user1637052 Aug 30 2018-12-12T00: 00Z
source share