22/10/2025, 01:32 problem_a.
cpp
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
// Function definition: f(x) = p + qx + rx^2 + sx^3 + tx^4
double f(double x) {
double p = 0.2, q = 25, r = -200, s = 675, t = -900,g=9.8 , m =68.1 , c=12.5;
// return (g*m/c)*(1-exp(-c*x/m));
return p + q*x + r*x*x + s*x*x*x + t*x*x*x*x;
}
// Trapezoidal rule for n intervals
double trapezoidal(double a, double b, int n) {
double h = (b - a) / n;
double sum = 0.5 * (f(a) + f(b));
for (int i = 1; i < n; i++) {
sum += f(a + i*h);
}
return sum * h;
}
// For valid input of limits value
double limit_in(string prompt) {
double val;
while (true) {
cout << prompt;
if (cin >> val) {
return val;
} else {
cout << "Please enter a valid number.\n";
[Link](); // clear error flag
[Link](1000, '\n'); // discard invalid input
}
}
}
// Romberg Integration with table printing
void rombergTable(double a, double b, int maxLevel) {
double R[20][20]; // Romberg table
R[0][0] = trapezoidal(a, b, 1);
cout << fixed << setprecision(6);
cout << "Romberg Integration Table:\n";
cout << "Level\t";
for(int i=1;i<= maxLevel;i++){
cout<<"O(h^"<<(int)pow(2,i) <<") \t\t";
}
cout<<endl;
// print first row
cout << "1\t" << R[0][0] << "\n";
for (int i = 1; i < maxLevel; i++) {
// First column: trapezoidal with 2^i intervals
R[i][0] = trapezoidal(a, b, 1 << i);
// Richardson extrapolation
for (int k = 1; k <= i; k++) {
R[i][k] = (pow(4, k) * R[i][k-1] - R[i-1][k-1]) / (pow(4, k) - 1);
}
// Print current row
cout << i+1 << "\t";
for (int k = 0; k <= i; k++) {
cout << R[i][k] << "\t";
[Link] 1/2
22/10/2025, 01:32 problem_a.cpp
}
cout << "\n";
}
}
int main() {
int n;
double a = limit_in("Enter lower limit: ");
double b = limit_in("Enter upper limit: ");
cout << "Enter Romberg levels (e.g. 5 or 6): ";
cin >> n;
rombergTable(a, b, n);
return 0;
}
[Link] 2/2