22/10/2025, 01:32 problem_b.
cpp
#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
using namespace std;
// Function: v(t) = k1*(1 - exp(-k2*t))
double fun(double x)
{
double p = 0.2, q = 25, r = -200, s = 675, t = -900,g=9.8 , m =68.1 , c=12.5;
double k1 = g * m / c;
double k2 = -(c / m);
return k1 * (1 - exp(k2 * x));
return p + q*x + r*x*x + s*x*x*x + t*x*x*x*x;
// Limit input (always a number)
double lim_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
}
}
}
// Gauss–Legendre 2-point
double gauss_legendre_2pt(double (*f)(double),double a, double b)
{
double x1 = -1.0 / sqrt(3.0), x2 = 1.0 / sqrt(3.0);
double w1 = 1.0, w2 = 1.0;
auto transform = [&](double x)
{
return 0.5 * ((b - a) * x + (b + a));
};
double I = 0.5 * (b - a) *
(w1 * f(transform(x1)) +
w2 * f(transform(x2)));
return I;
}
// Gauss–Legendre 3-point
double gauss_legendre_3pt(double (*f)(double),double a, double b)
{
double x0 = 0.0;
double x1 = -sqrt(3.0 / 5.0);
double x2 = sqrt(3.0 / 5.0);
double w0 = 8.0 / 9.0, w1 = 5.0 / 9.0, w2 = 5.0 / 9.0;
auto transform = [&](double x)
{
[Link] 1/2
22/10/2025, 01:32 problem_b.cpp
return 0.5 * ((b - a) * x + (b + a));
};
double I = 0.5 * (b - a) *
(w0 * f(transform(x0)) +
w1 * f(transform(x1)) +
w2 * f(transform(x2)));
return I;
}
// 4-point Gauss-Legendre Quadrature
double gauss_legendre_4pt(double (*f)(double),
double a, double b) {
// Nodes
double x[4] = { -0.8611363115940526, -0.3399810435848563,
0.3399810435848563, 0.8611363115940526 };
// Weights
double w[4] = { 0.3478548451374539, 0.6521451548625461,
0.6521451548625461, 0.3478548451374539 };
auto transform = [&](double x) {
return 0.5 * ((b - a) * x + (b + a));
};
double I = 0.0;
for (int i = 0; i < 4; i++) {
I += w[i] * f(transform(x[i]));
}
I *= 0.5 * (b - a);
return I;
}
int main()
{
cout << "Gauss Legendre Quadrature for v(t) = (gm/c)*(1 - exp(-(c/m)*t))\n";
// Default coefficients
double a = lim_in("Enter lower limit: ");
double b = lim_in("Enter upper limit: ");
double I2 = gauss_legendre_2pt(fun, a, b);
double I3 = gauss_legendre_3pt(fun, a, b);
double I4 = gauss_legendre_4pt(fun,a,b);
cout << "\n----------- Output -----------\n";
cout << "2-point Gauss-Legendre Integral : " << fixed << setprecision(6) << I2 <<
"\n";
cout << "3-point Gauss-Legendre Integral : " << fixed << setprecision(6) << I3 <<
"\n";
cout << "4-point Gauss-Legendre Integral : " << fixed << setprecision(6) << I4 <<
"\n";
cout << "--------------------------------\n";
return 0;
}
[Link] 2/2