Advertisement
MeShootIn

Trapezoidal rule

Apr 19th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.61 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. typedef double (* function) (double x);
  6.  
  7. double f(double x){
  8.     return x;
  9. }
  10.  
  11. double X(int i, double a, double h){
  12.     return a + i * h;
  13. }
  14.  
  15. double Trapezoidal(double a, double b, int N, function f){
  16.     double h = (b - a) / double(N);
  17.    
  18.     double S = 0;
  19.     for(int i = 1; i <= N; ++i){
  20.         S += h * (f(X(i - 1, a, h)) + f(X(i, a, h))) / 2.;
  21.     }
  22.    
  23.     return S;
  24. }
  25.  
  26. int main(){
  27.     double a, b;
  28.     cout << "Enter a, b:\n";
  29.     cin >> a >> b;
  30.    
  31.     cout << "Enter the number of segments:\n";
  32.     int N;
  33.     cin >> N;
  34.    
  35.     cout << Trapezoidal(a, b, N, f);
  36.    
  37.     system("PAUSE");
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement