Advertisement
Guest User

Untitled

a guest
Nov 24th, 2014
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.23 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. double FX(double x) {
  5.     return x;
  6. }
  7.  
  8. double FXX(double x) {
  9.     return x * x;
  10. }
  11.  
  12. double MetodSrednihPryamougolnikov(double a, double b, double countOfParts, double(*func)(double)) {
  13.     double sum = (func(a) + func(b)) / 2.0, step = (b - a) / countOfParts;
  14.     for(double x = a + step; x < b; x += step)
  15.         sum += func(x);
  16.     return sum / countOfParts;
  17. }
  18.  
  19. double MetodLevihPryamougolnikov(double a, double b, double countOfParts, double(*func)(double)) {
  20.     double sum = 0, step = (b - a) / countOfParts;
  21.     for(double x = a; x < b; x += step)
  22.         sum += func(x);
  23.     return sum / countOfParts;
  24. }
  25.  
  26. double MetodPravihPryamougolnikov(double a, double b, double countOfParts, double(*func)(double)) {
  27.     double sum = 0, step = (b - a) / countOfParts;
  28.     for(double x = b; x > a; x -= step)
  29.         sum += func(x);
  30.     return sum / countOfParts;
  31. }
  32.  
  33. double CalcIntegral(double a, double b, double eps, double(*method)(double, double, double, double(*func)(double)), double(*func)(double)) {
  34.     double countOfParts = 4, lastIntegral = method(a, b, countOfParts, func), currentIntegral, diff;
  35.     do {
  36.         currentIntegral = method(a, b, (countOfParts *= 2), func);
  37.         diff = fabs(lastIntegral - currentIntegral);
  38.         lastIntegral = currentIntegral;
  39.     } while(diff > eps);
  40.     return lastIntegral;
  41. }
  42.  
  43. int main() {
  44.     double a, b, eps;
  45.     std::cout << "Get a:";
  46.     std::cin >> a;
  47.     std::cout << "Get b:";
  48.     std::cin >> b;
  49.     std::cout << "Get eps:";
  50.     std::cin >> eps;
  51.  
  52.     std::cout << "(f = x,   MetodLevihPryamougolnikov):  " << CalcIntegral(a, b, eps, MetodLevihPryamougolnikov,    FX)  << std::endl; 
  53.     std::cout << "(f = x,   MetodSrednihPryamougolnikov):" << CalcIntegral(a, b, eps, MetodSrednihPryamougolnikov,  FX)  << std::endl;
  54.     std::cout << "(f = x,   MetodPravihPryamougolnikov): " << CalcIntegral(a, b, eps, MetodPravihPryamougolnikov,   FX)  << std::endl;
  55.     std::cout << "(f = x*x, MetodLevihPryamouholnikov):  " << CalcIntegral(a, b, eps, MetodLevihPryamougolnikov,    FXX) << std::endl;
  56.     std::cout << "(f = x*x, MetodSrednihPryamougolnikov):" << CalcIntegral(a, b, eps, MetodSrednihPryamougolnikov,  FXX) << std::endl;
  57.     std::cout << "(f = x*x, MetodPravihPryamouholnikov): " << CalcIntegral(a, b, eps, MetodPravihPryamougolnikov,   FXX) << std::endl;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement