Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template <typename F>
- class IntegrationMethod {
- public:
- virtual double Integrate(F func, double a, double b, int n) {}
- };
- template <typename F>
- class RectangleRule : public IntegrationMethod<F> {
- private:
- double result;
- double x1, x2;
- public:
- double Integrate(F func, double a, double b, int n) {
- x2 = a;
- for (int i = 0; i < n; i++) {
- x1 = x2;
- x2 = a + ((b - a) / n) * (i + 1);
- result += F((x1 + x2) / 2) * (x2 - x1);
- }
- return result;
- }
- };
- template <typename F>
- class TrapezoidalRule : public IntegrationMethod<F> {
- private:
- double result;
- double x1, x2;
- public:
- double Integrate(F func, double a, double b, int n) {
- x2 = a;
- for (int i = 0; i < n; i++) {
- x1 = x2;
- x2 = a + ((b - a) / n) * (i + 1);
- result += ((F(x1) + F(x2)) / 2) * (x2 - x1);
- }
- return result;
- }
- };
- #include <cmath>
- #include <iostream>
- #include <memory>
- #include <string>
- int main() {
- using F = decltype(cos);
- std::string input;
- std::cin >> input;
- std::unique_ptr<IntegrationMethod<F>> method;
- if (input == "rectangle")
- method.reset(new RectangleRule<F>);
- else
- method.reset(new TrapezoidalRule<F>);
- double x, y;
- std::cin >> x >> y;
- int n;
- std::cin >> n;
- std::cout << method->Integrate(cos, x, y, n) << "\n";
- std::cout << method->Integrate(sin, x, y, n) << "\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement