fork download
  1. /*
  2. Function to get the maximum possible number of places a numeric type could hypothetically represent under ideal circumstances.
  3. Copyright (C) 2015 Peter R. Bloomfield
  4. Web: avidinsight.uk
  5.  
  6. This code is made freely available under the terms of the MIT open source license.
  7. */
  8.  
  9. #include <iostream>
  10. #include <cmath>
  11. #include <limits>
  12.  
  13. using namespace std;
  14.  
  15. // Get the maximum number of radix
  16. template <typename T_type, int T_radix>
  17. int getMaxPlaces()
  18. {
  19. static_assert(
  20. T_radix > 1,
  21. "Radix must be at least 2."
  22. );
  23. static_assert(
  24. std::numeric_limits<T_type>::is_specialized,
  25. "Numeric limits traits info not found."
  26. );
  27.  
  28. // Integers contain no point.
  29. if (std::numeric_limits<T_type>::is_integer)
  30. return 0;
  31.  
  32. // Maximum number of places in the native radix.
  33. const int places =
  34. std::abs(std::numeric_limits<T_type>::min_exponent) +
  35. std::numeric_limits<T_type>::digits;
  36.  
  37. // Special case: If the requested radix matches the underlying radix
  38. // specified in traits then no base conversion is necessary.
  39. if (T_radix == std::numeric_limits<T_type>::radix)
  40. return places;
  41.  
  42. // Convert the number of places to the requested radix.
  43. return static_cast<int>( std::ceil(
  44. places *
  45. std::log(std::numeric_limits<T_type>::radix) /
  46. std::log(T_radix)
  47. ));
  48. }
  49.  
  50. int main() {
  51. cout << "int: " << getMaxPlaces<int, 10>() << endl;
  52. cout << "float: " << getMaxPlaces<float, 10>() << endl;
  53. cout << "double: " << getMaxPlaces<double, 10>() << endl;
  54. cout << "long double: " << getMaxPlaces<long double, 10>() << endl;
  55. return 0;
  56. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
int:         0
float:       45
double:      324
long double: 4951