Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- // Function to integrate
- double f(double x) {
- return x * x * x; // Example function x^2
- }
- // Trapezoidal rule function
- double trapezoidal(double a, double b, int n) {
- double h = (b - a) / n; // Width of each trapezoid
- double sum = 0.5 * (f(a) + f(b)); // Sum of the first and last terms
- for (int i = 1; i < n; ++i) {
- double x = a + i * h; // Current x value
- sum = sum + f(x); // Add f(x_i)
- }
- return sum * h;
- }
- int main() {
- double a, b; // Integration limits
- int n; // Number of subdivisions
- // Input values
- cout << "Enter lower limit of integration: ";
- cin >> a;
- cout << "Enter upper limit of integration: ";
- cin >> b;
- cout << "Enter the number of subdivisions: ";
- cin >> n;
- // Calculate integral using trapezoidal rule
- double integral = trapezoidal(a, b, n);
- // Output result
- cout << "Approximate integral: " << integral << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement