Advertisement
Dzham

Untitled

Jan 25th, 2018
104
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 += func((x1 + x2) / 2) * (x2 - x1);
  19. }
  20. return result;
  21. }
  22. };
  23.  
  24. template <typename F>
  25. class TrapezoidalRule : public IntegrationMethod<F> {
  26. public:
  27. double Integrate(F func, double a, double b, int n) {
  28. double result;
  29. double x1;
  30. double x2 = a;
  31. for (int i = 0; i < n; i++) {
  32. x1 = x2;
  33. x2 = a + ((b - a) / n) * (i + 1);
  34. result += ((func(x1) + func(x2)) / 2) * (x2 - x1);
  35. }
  36. return result;
  37. }
  38. };
  39.  
  40. #include <cmath>
  41. #include <iostream>
  42. #include <memory>
  43. #include <string>
  44.  
  45. int main() {
  46. using F = decltype(cos);
  47.  
  48. std::string input;
  49. std::cin >> input;
  50. std::unique_ptr<IntegrationMethod<F>> method;
  51. if (input == "rectangle")
  52. method.reset(new RectangleRule<F>);
  53. else
  54. method.reset(new TrapezoidalRule<F>);
  55.  
  56. double x, y;
  57. std::cin >> x >> y;
  58.  
  59. int n;
  60. std::cin >> n;
  61.  
  62. std::cout << method->Integrate(cos, x, y, n) << "\n";
  63. std::cout << method->Integrate(sin, x, y, n) << "\n";
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement