thespeedracer38

Trapezoidal Method by Me

Jan 31st, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. using namespace std;
  5.  
  6. class TrapezoidalRule{
  7.     double *y;
  8.     int n;
  9.     double h, a, b;
  10.     public:
  11.         TrapezoidalRule(double, double, int);
  12.         ~TrapezoidalRule();
  13.         double f(double);
  14.         double calcSolution();
  15.         void displaySolution();
  16. };
  17.  
  18. TrapezoidalRule::TrapezoidalRule(double a, double b, int n){
  19.     TrapezoidalRule::a = a;
  20.     TrapezoidalRule::b = b;
  21.     TrapezoidalRule::n = n;
  22.    
  23.     y = new double[n + 1];
  24.     h = (a - b) / n;
  25. }
  26.  
  27. TrapezoidalRule::~TrapezoidalRule(){
  28.     delete y;
  29. }
  30.  
  31. double TrapezoidalRule::f(double x){
  32.     return 4.0 / (1 + (x * x));
  33. }
  34.  
  35. double TrapezoidalRule::calcSolution(){
  36.     // Generate all value of y0 to yn
  37.     for(int x = 0; x <= n; x++){
  38.         y[x] = f(x);
  39.     }
  40.     // Calculating the value of I
  41.     double i = 0;
  42.     double sum = 0;
  43.     for(int i = 1; i < n; i++){
  44.         sum += y[i];
  45.     }
  46.     sum *= 2;
  47.     sum += (y[0] + y[n]);
  48.     i = (1.0/2.0) * h * sum;
  49.     return i;
  50. }
  51.  
  52. void TrapezoidalRule::displaySolution(){
  53.     cout << "I = " << calcSolution();
  54. }
  55.  
  56. int main(int argc, char** argv) {
  57.     system("cls");
  58.     TrapezoidalRule obj(1, 0, 10);
  59.     obj.displaySolution();
  60.     cin.get();
  61.     return 0;
  62. }
Add Comment
Please, Sign In to add comment