fork(1) download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <random>
  4. #include <cmath>
  5.  
  6. using namespace std;
  7.  
  8. // Funkcja do całkowania
  9. long double f(long double x) {
  10. return 4.0L / (1.0L + x * x);
  11. }
  12.  
  13. int main() {
  14. long long n;
  15. cin >> n; // liczba losowań / podziałów
  16.  
  17. // =========================
  18. // 1. MONTE CARLO
  19. // =========================
  20. mt19937_64 gen(random_device{}());
  21. uniform_real_distribution<long double> dist(-1.0L, 1.0L);
  22.  
  23. long long inside = 0;
  24.  
  25. for (long long i = 0; i < n; i++) {
  26. long double x = dist(gen);
  27. long double y = dist(gen);
  28.  
  29. if (x * x + y * y <= 1.0L)
  30. inside++;
  31. }
  32.  
  33. long double pi_monte = 4.0L * inside / n;
  34.  
  35. // =========================
  36. // 2. METODA PROSTOKĄTÓW
  37. // =========================
  38. long double dx = 1.0L / n;
  39. long double sum_rect = 0.0L;
  40.  
  41. for (long long i = 0; i < n; i++) {
  42. long double x = (i + 0.5L) * dx; // punkt środkowy
  43. sum_rect += f(x);
  44. }
  45.  
  46. long double pi_rect = sum_rect * dx;
  47.  
  48. // =========================
  49. // 3. METODA TRAPEZÓW
  50. // =========================
  51. long double sum_trap = (f(0.0L) + f(1.0L)) / 2.0L;
  52.  
  53. for (long long i = 1; i < n; i++) {
  54. long double x = i * dx;
  55. sum_trap += f(x);
  56. }
  57.  
  58. long double pi_trap = sum_trap * dx;
  59.  
  60. // =========================
  61. // WYNIKI
  62. // =========================
  63. cout << fixed << setprecision(20);
  64. cout << pi_monte << endl;
  65. cout << pi_rect << endl;
  66. cout << pi_trap << endl;
  67.  
  68. return 0;
  69. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
-nan
-nan
inf