Gistrec

ПВ численное интегрирование

May 1st, 2019
274
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4.  
  5. /// Значение функции в точке x
  6. double function(double x) {
  7.     return x*x*x*x + x*x + 2.0;
  8. }
  9.  
  10. /// Значение второй производной в точке x
  11. double seconddif(double x, double h) {
  12.     //u''(x) = 1 / hi ((ui+1-ui) / hi + 1 - (ui-ui-1) / hi)
  13.     double f1 = function(x);
  14.     double f2 = function(x + h);
  15.     double f3 = function(x - h);
  16.     return (f2 - 2.0 * f1 + f3) / (h * h);
  17. }
  18.  
  19. double CalcRectangle(double a, double b, int n) {
  20.     double result = 0;
  21.     double h = (b - a) / n; // Шаг сетки
  22.  
  23.     for(int i = 0; i < n; i++) {
  24.         // a + h * (i + 0.5) - X координата середины узла
  25.         result += function(a + h * (i + 0.5));
  26.         // std::cout << result << std::endl;
  27.     }
  28.  
  29.     result *= h;
  30.  
  31.     result += seconddif((a + b) / 2.0, h) * h * h * (b - a) / 24.0;
  32.  
  33.     return result;
  34. }
  35.  
  36.  
  37. double CalcTrapeze(double a, double b, int n) {
  38.     double result = 0;
  39.     double h = (b - a) / n; // Шаг сетки
  40.  
  41.  
  42.     for (int i = 1; i < n; i++) {
  43.         // a + h * i - X координата узла
  44.         result += function(a + h * i);
  45.     }
  46.     result += (function(a) + function(b)) / 2.0;
  47.     result *= h;
  48.     result -= h * h * (b - a) * seconddif((a + b) / 2.0, h) / 12.0 ;
  49.  
  50.     return result;
  51. }
  52.  
  53.  
  54. int main() {
  55.     double integral = CalcRectangle(0, 5, 1);
  56.     std::cout << integral << std::endl;
  57.  
  58.     integral = CalcRectangle(0, 5, 2);
  59.     std::cout << integral << std::endl;
  60.  
  61.     integral = CalcRectangle(0, 5, 4);
  62.     std::cout << integral << std::endl;
  63.  
  64.     std::cout << std::endl;
  65.  
  66.     integral = CalcTrapeze(0, 5, 1);
  67.     std::cout << integral << std::endl;
  68.  
  69.     integral = CalcTrapeze(0, 5, 2);
  70.     std::cout << integral << std::endl;
  71.  
  72.     integral = CalcTrapeze(0, 5, 4);
  73.     std::cout << integral << std::endl;
  74.  
  75.     return 0;
  76. }
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment