With a lower limit of 0, upper limit of 2, I was told that there is a problem with my program. I was told "This program contains an error, and as result is not giving correct values. Use your mathematical knowledge of the Trapezoidal and Midpoint Rules to explain how you can tell, by looking at the output, that there is an error. Correct the error, run your corrected program, import to SWP, and make a corrected table. Compare the new table to the old one, not only for accuracy of values, but for speed of convergence" Any idea what I did wrong? Having trouble seeing it myself.
// A program to approximate a definite integal by the trapezoidal rule.
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <math.h>
#include <iomanip>
usingnamespace std;
double f(double); // function prototype
int main(void)
{
constint s = 30; // maximum number of steps
double a, b, tol; // lower and upper limits, tolerance
double n = 1; // number of intervals; doubles each time through loop.
double T, M; // trapezoidal and midpoint rule estimates
double x; // value of x
double sum; // sum in midpoint computation
double h; // length of an interval
char zzz; // holds screen
constchar filepath[] = "C:\\CoutputFiles\\File5.txt";
constchar ErrorMessage[] = "Can't open file ";
fstream OutStream(filepath, ios::out);
if (OutStream.fail())
{
cerr << ErrorMessage << filepath;
cin >> zzz;
exit(-1);
}
cout << "Enter the lower and upper limits and the tolerance, separated by spaces\n";
cin >> a >> b >> tol;
OutStream << setprecision(10);
h = b - a;
T = (f(a) + f(b)) / 2;
for (int i = 1; i <= s; i++)
{
// compute Midpoint formula
sum = 0;
x = a + h / 2;
for (int j = 1; j <= n; j++)
{
sum += f(x);
x += h;
}
M = h*sum;
// Output to file
OutStream << i << ", " << T << ", " << M << ", ";
if (fabs(T - M) < tol)
break;
// Update Trapezoidal, h, n
T = (T + M) / 2;
n *= 2;
h /= 2;
}
cout << "Enter a character to end.\n";
cin >> zzz;
return 0;
}
double f(double x)
{
return x*x*x;
}
Oh, my bad. I thought that the X values weren't right and I was trying to get you to see it. Sorry.
y=x3 is convex from 0 to 2: it curves up. Knowing just that, what can you say about the trapezoidal estimate vs. the midpoint estimate. One is guaranteed to be larger than the other (I think). Which one is larger? Does the program output show that?