fork(1) download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <random>
  4. #include <cmath>
  5.  
  6. using namespace std;
  7.  
  8. // Funkcja podcałkowa
  9. long double f(long double x) {
  10. return sqrt(1.0L - x * x);
  11. }
  12.  
  13. int main() {
  14. long long n;
  15. cout << "Podaj liczbe losowan / podzialow (n): ";
  16. cin >> n;
  17.  
  18. // =========================
  19. // 1. METODA MONTE CARLO
  20. // =========================
  21. random_device rd;
  22. mt19937_64 gen(rd());
  23. uniform_real_distribution<long double> dist(-1.0L, 1.0L);
  24.  
  25. long long inside = 0;
  26.  
  27. for (long long i = 0; i < n; i++) {
  28. long double x = dist(gen);
  29. long double y = dist(gen);
  30.  
  31. if (x * x + y * y <= 1.0L) {
  32. inside++;
  33. }
  34. }
  35.  
  36. long double pi_monte_carlo = 4.0L * inside / n;
  37.  
  38. // =========================
  39. // 2. METODA PROSTOKĄTÓW
  40. // =========================
  41. long double h = 1.0L / n;
  42. long double sum_rect = 0.0L;
  43.  
  44. for (long long i = 0; i < n; i++) {
  45. long double x = i * h;
  46. sum_rect += f(x);
  47. }
  48.  
  49. long double pi_rect = 4.0L * h * sum_rect;
  50.  
  51. // =========================
  52. // 3. METODA TRAPEZÓW
  53. // =========================
  54. long double sum_trap = (f(0.0L) + f(1.0L)) / 2.0L;
  55.  
  56. for (long long i = 1; i < n; i++) {
  57. long double x = i * h;
  58. sum_trap += f(x);
  59. }
  60.  
  61. long double pi_trap = 4.0L * h * sum_trap;
  62.  
  63. // =========================
  64. // WYNIKI
  65. // =========================
  66. cout << fixed << setprecision(20);
  67.  
  68. cout << "\nPrzyblizenie liczby pi:\n";
  69. cout << "Monte Carlo : " << pi_monte_carlo << endl;
  70. cout << "Prostokaty : " << pi_rect << endl;
  71. cout << "Trapezy : " << pi_trap << endl;
  72.  
  73. return 0;
  74. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Podaj liczbe losowan / podzialow (n): 
Przyblizenie liczby pi:
Monte Carlo  : -nan
Prostokaty   : -nan
Trapezy      : inf