fork download
  1. #include <iostream>
  2. #include <cmath>
  3. #include <iomanip>
  4. using namespace std;
  5.  
  6. // f(x) = sqrt(1 - x^2)
  7. double f(double x) {
  8. return sqrt(1.0 - x * x);
  9. }
  10.  
  11. // Metoda prostokątów (środek przedziału)
  12. double metodaProstokatow(double a, double b, int n) {
  13. double h = (b - a) / n;
  14. double suma = 0.0;
  15.  
  16. for(int i = 0; i < n; i++) {
  17. double x = a + (i + 0.5) * h;
  18. suma += f(x);
  19. }
  20.  
  21. return 2.0 * h * suma;
  22. }
  23.  
  24. // Metoda trapezów
  25. double metodaTrapezow(double a, double b, int n) {
  26. double h = (b - a) / n;
  27. double suma = 0.5 * (f(a) + f(b));
  28.  
  29. for(int i = 1; i < n; i++) {
  30. double x = a + i * h;
  31. suma += f(x);
  32. }
  33.  
  34. return 2.0 * h * suma;
  35. }
  36.  
  37. int main() {
  38. double a = -1.0;
  39. double b = 1.0;
  40. int n = 1000000; // liczba podprzedziałów
  41.  
  42. double piProstokaty = metodaProstokatow(a, b, n);
  43. double piTrapezy = metodaTrapezow(a, b, n);
  44.  
  45. cout << fixed << setprecision(20);
  46. cout << "π (metoda prostokatow): " << piProstokaty << endl;
  47. cout << "π (metoda trapezow): " << piTrapezy << endl;
  48. cout << "π (wartosc dokladna): " << acos(-1) << endl;
  49.  
  50. return 0;
  51. }
Success #stdin #stdout 0.02s 5324KB
stdin
Standard input is empty
stdout
π (metoda prostokatow): 3.14159265456397474026
π (metoda trapezow):    3.14159265026386957942
π (wartosc dokladna):   3.14159265358979311600