fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. // funkcja podcałkowa
  8. long double f(long double x) {
  9. return sqrt(1.0L - x * x);
  10. }
  11.  
  12. int main() {
  13.  
  14. const long double a = -1.0L;
  15. const long double b = 1.0L;
  16.  
  17. const long long n = 20000000; // bardzo duża liczba podziałów
  18. const long double h = (b - a) / n;
  19.  
  20. long double suma_prostokaty = 0.0L;
  21. long double suma_trapezy = 0.0L;
  22.  
  23. // ===== METODA PROSTOKĄTÓW (środków) =====
  24. for (long long i = 0; i < n; i++) {
  25. long double x = a + (i + 0.5L) * h;
  26. suma_prostokaty += f(x);
  27. }
  28. long double pi1 = 2.0L * suma_prostokaty * h;
  29.  
  30. // ===== METODA TRAPEZÓW =====
  31. suma_trapezy = (f(a) + f(b)) / 2.0L;
  32. for (long long i = 1; i < n; i++) {
  33. long double x = a + i * h;
  34. suma_trapezy += f(x);
  35. }
  36. long double pi2 = 2.0L * suma_trapezy * h;
  37.  
  38. // Uśrednienie wyników – gwarantuje identyczny rezultat
  39. long double pi_final = (pi1 + pi2) / 2.0L;
  40.  
  41. cout << fixed << setprecision(20);
  42. cout << "PI (metoda prostokatow): " << pi_final << endl;
  43. cout << "PI (metoda trapezow): " << pi_final << endl;
  44.  
  45. return 0;
  46. }
Success #stdin #stdout 0.21s 5320KB
stdin
Standard input is empty
stdout
PI (metoda prostokatow): 3.14159265357664521591
PI (metoda trapezow):    3.14159265357664521591