Advertisement
alansam

Polygon circumference/radius ratio.

Nov 25th, 2023 (edited)
791
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <algorithm>
  4. #include <cmath>
  5. #if defined(__cpp_lib_math_constants)
  6. # include <numbers>
  7. #endif
  8.  
  9. //  π(n) = n . sin(180 / n)
  10.  
  11. #define FUNCTIONAL_
  12.  
  13. #if defined(__cpp_lib_math_constants)
  14. constexpr
  15. double pi = std::numbers::pi_v<double>;
  16. #elif defined(M_PI)
  17. constexpr
  18. double pi = M_PI;
  19. #else
  20. constexpr
  21. double pi = 2.0 * std::acos(0.0);
  22. #endif
  23.  
  24. auto to_radian = [](double angle) { return angle * (pi / 180.0); };
  25. auto poly_pi_l = [](long sides) {
  26.   return (1.0 * sides) * std::sin(to_radian(180.0) / (1.0 * sides));
  27. };
  28. auto poly_pi = [](long sides) { return (1.0 * sides) * std::sin(pi / (1.0 * sides)); };
  29.  
  30. int main() {
  31.   std::cout << "C++ Version: " << __cplusplus << '\n';
  32. #if defined(__cpp_lib_math_constants)
  33.   std::cout << "C++ Math Constants Version: " << __cpp_lib_math_constants << '\n';
  34. #endif
  35.  
  36.   std::cout << std::fixed << std::setprecision(12);
  37.   std::cout << "π: " << pi << '\n';
  38.  
  39.   auto polygons = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 50, 100, 200, 500,
  40.                          1'000,      5'000,
  41.                         10'000,     20'000,
  42.                        100'000,    200'000,
  43.                        200'000,    400'000,
  44.                      1'000'000,  2'000'000,  3'000'000,
  45.                      4'000'000,  4'100'000,  4'200'000,
  46.                     10'000'000, 20'000'000, 25'000'000, };
  47.  
  48. #ifndef FUNCTIONAL_
  49.   std::cout << std::string(60, '=') << std::endl;
  50.  
  51.   for (auto side : polygons) {
  52.     std::cout << std::setw(12) << side << " : "
  53.               << std::setw(15) << poly_pi(side)
  54.               << " - "
  55.               << std::setw(15) << poly_pi_l(side)
  56.               << '\n';
  57.   }
  58. #else
  59.   std::cout << std::string(60, '.') << std::endl;
  60.  
  61.   std::for_each(polygons.begin(), polygons.end(), [](auto const side) {
  62.     std::cout << std::setw(12) << side << " : "
  63.               << std::setw(15) << poly_pi(side)
  64.               << " - "
  65.               << std::setw(15) << poly_pi_l(side)
  66.               << '\n';
  67.   });
  68. #endif
  69.  
  70.   return 0;
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement