Advertisement
Dzham

Untitled

Jan 24th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. template <typename F>
  2. class IntegrationMethod {
  3. public:
  4. virtual double Integrate(F func, double a, double b, int n) {}
  5. };
  6.  
  7. template <typename F>
  8. class RectangleRule : public IntegrationMethod<F> {
  9. private:
  10. double result;
  11. double x1, x2;
  12. public:
  13. double Integrate(F func, double a, double b, int n) {
  14. x2 = a;
  15. for (int i = 0; i < n; i++) {
  16. x1 = x2;
  17. x2 = a + ((b - a) / n) * (i + 1);
  18. result += F((x1 + x2) / 2) * (x2 - x1);
  19. }
  20. return result;
  21. }
  22. };
  23.  
  24. template <typename F>
  25. class TrapezoidalRule : public IntegrationMethod<F> {
  26. private:
  27. double result;
  28. double x1, x2;
  29. public:
  30. double Integrate(F func, double a, double b, int n) {
  31. x2 = a;
  32. for (int i = 0; i < n; i++) {
  33. x1 = x2;
  34. x2 = a + ((b - a) / n) * (i + 1);
  35. result += ((F(x1) + F(x2)) / 2) * (x2 - x1);
  36. }
  37. return result;
  38. }
  39. };
  40.  
  41.  
  42.  
  43.  
  44.  
  45. #include <cmath>
  46. #include <iostream>
  47. #include <memory>
  48. #include <string>
  49.  
  50. int main() {
  51. using F = decltype(cos);
  52.  
  53. std::string input;
  54. std::cin >> input;
  55. std::unique_ptr<IntegrationMethod<F>> method;
  56. if (input == "rectangle")
  57. method.reset(new RectangleRule<F>);
  58. else
  59. method.reset(new TrapezoidalRule<F>);
  60.  
  61. double x, y;
  62. std::cin >> x >> y;
  63.  
  64. int n;
  65. std::cin >> n;
  66.  
  67. std::cout << method->Integrate(cos, x, y, n) << "\n";
  68. std::cout << method->Integrate(sin, x, y, n) << "\n";
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement