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 4.0L / (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. long double pi_monte_carlo = 4.0L * inside / n;
  36.  
  37. // =========================
  38. // 2. METODA PROSTOKĄTÓW
  39. // =========================
  40. long double dx = 1.0L / n;
  41. long double sum_rect = 0.0L;
  42.  
  43. for (long long i = 0; i < n; i++) {
  44. long double x = i * dx; // lewy punkt
  45. sum_rect += f(x);
  46. }
  47.  
  48. long double pi_rect = sum_rect * dx;
  49.  
  50. // =========================
  51. // 3. METODA TRAPEZÓW
  52. // =========================
  53. long double sum_trap = (f(0.0L) + f(1.0L)) / 2.0L;
  54.  
  55. for (long long i = 1; i < n; i++) {
  56. long double x = i * dx;
  57. sum_trap += f(x);
  58. }
  59.  
  60. long double pi_trap = sum_trap * dx;
  61.  
  62. // =========================
  63. // WYNIKI
  64. // =========================
  65. cout << fixed << setprecision(20);
  66. cout << "\nPrzyblizenie liczby pi:\n";
  67. cout << "Monte Carlo : " << pi_monte_carlo << endl;
  68. cout << "Prostokaty : " << pi_rect << endl;
  69. cout << "Trapezy : " << pi_trap << endl;
  70.  
  71. return 0;
  72. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Podaj liczbe losowan / podzialow n: 
Przyblizenie liczby pi:
Monte Carlo  : -nan
Prostokaty   : -nan
Trapezy      : inf