Advertisement
anik11556

trepezidal

Feb 12th, 2024
950
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Function to integrate
  5. double f(double x) {
  6.     return x * x * x; // Example function x^2
  7. }
  8.  
  9. // Trapezoidal rule function
  10. double trapezoidal(double a, double b, int n) {
  11.     double h = (b - a) / n; // Width of each trapezoid
  12.     double sum = 0.5 * (f(a) + f(b)); // Sum of the first and last terms
  13.    
  14.     for (int i = 1; i < n; ++i) {
  15.         double x = a + i * h; // Current x value
  16.         sum = sum + f(x); // Add f(x_i)
  17.     }
  18.    
  19.     return sum * h;
  20. }
  21.  
  22. int main() {
  23.     double a, b; // Integration limits
  24.     int n; // Number of subdivisions
  25.    
  26.     // Input values
  27.     cout << "Enter lower limit of integration: ";
  28.     cin >> a;
  29.     cout << "Enter upper limit of integration: ";
  30.     cin >> b;
  31.     cout << "Enter the number of subdivisions: ";
  32.     cin >> n;
  33.    
  34.     // Calculate integral using trapezoidal rule
  35.     double integral = trapezoidal(a, b, n);
  36.    
  37.     // Output result
  38.     cout << "Approximate integral: " << integral << endl;
  39.    
  40.     return 0;
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement