fork(1) download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. // funkcja półokręgu
  7. double f(double x) {
  8. return sqrt(1 - x * x);
  9. }
  10.  
  11. int main() {
  12. int n = 100000; // liczba podziałów
  13. double a = -1.0;
  14. double b = 1.0;
  15. double h = (b - a) / n;
  16.  
  17. // --- METODA PROSTOKĄTÓW ---
  18. double suma_rect = 0.0;
  19. for(int i = 0; i < n; i++) {
  20. double x = a + i * h;
  21. suma_rect += f(x);
  22. }
  23. double pi_rect = 2 * h * suma_rect;
  24.  
  25.  
  26. // --- METODA TRAPEZÓW ---
  27. double suma_trap = 0.5 * (f(a) + f(b));
  28. for(int i = 1; i < n; i++) {
  29. double x = a + i * h;
  30. suma_trap += f(x);
  31. }
  32. double pi_trap = 2 * h * suma_trap;
  33.  
  34. // Wyniki
  35. cout << "Metoda prostokatow: " << pi_rect << endl;
  36. cout << "Metoda trapezow: " << pi_trap << endl;
  37. cout << "Wartosc M_PI: " << M_PI << endl;
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Metoda prostokatow: 3.14159
Metoda trapezow:    3.14159
Wartosc M_PI:       3.14159