Problem with Program

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// A program to approximate a definite integal by the trapezoidal rule.
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <math.h>
#include <iomanip>

using namespace std;

double f(double); // function prototype
int main(void)
{
	const int 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
	const char filepath[] = "C:\\CoutputFiles\\File5.txt";
	const char 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;
}

Last edited on
Add code between lines 41 and 42 to print x. I think you'll find that the values aren't what you expect.
So I should try to return x*x*x between line 41 and 42?
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?
Topic archived. No new replies allowed.