Portable floating point variable patterns

How to define portable high-precision floating point variable patterns in C ++ 14? The program below should print pi with the precision of double and long double .

 #include <iostream> #include <iomanip> #include <limits> template<typename T> constexpr T pi = T(3.141592653589793238462643383279502884197); int main() { std::cout << std::setprecision(std::numeric_limits<double>::max_digits10) << pi<double> << std::endl; std::cout << std::setprecision(std::numeric_limits<long double>::max_digits10) << pi<long double> << std::endl; } 

When I compile with GCC 5.1.0 g++ -std=c++14 , I get

 3.1415926535897931 3.141592653589793116 

I assume gcc converts the number to double and then applies the pattern. I do not think that the literal L is the answer, because I do not want to rewrite when I go to float128 or higher. How can I make the compiler keep all the accuracy?

+1
source share
1 answer

All floating point literals, unless otherwise specified, are of type double . The fact that you use it as an initializer for T (regardless of T may be) does not matter, you are still going to initialize pi using a double converted to T

The suffix of the literal with l to make it a long double , which is then converted to T

+4
source

Source: https://habr.com/ru/post/1235099/


All Articles