//============================================================\\ // VTrap 1.0 // Implementation of the Trapezoidal Rule. // Integrates f(x) from b to a, n iterations. // n shoudl be within 1 to // Written by V'lion 2002. // Contect me at pdn@rmci.net // Please visit my 4D engine site at http://thefivelions.tripod.com/bugle4d/ //============================================================// #include #include /* Implementation of the trapezoidal rule. all var names are direct from it. deltax = (b-a)/n (deltax/2)(y0+2y1+...+2y(n-1) + yn) */ double f(double x) { return (x*x*x); } void main() { double b, a, deltax, acc = 0; unsigned int n; cout << "Numerical integration according to the trapezoidal rule.\nRecommend n be a large number.\n"; cout << " /b\n" << " /\n" << " |\n" << " | f(x) dx\n" << " |\n" << " /\n" << "/a\n" << "n is the iteration number.\n" << "\n"; cout << "b: "; cin >> b; cout << "a: "; cin >> a; cout << "n: "; cin >> n; //Error checks. if(b < a) { cout << "b less than a !" << "Errornous result avoided." << "Program shutting down."; return; } if(!n) { cout << "n is zero !\n" << "Divide by zero avoided;\n" << "Program shutting down."; return; } //DX calculated deltax = (b-a)/n; //Alg run. for(double i = a + deltax; i <= (b - deltax); i+= deltax) { acc += 2*f(i); } //Result calculated and displayed cout << "\n Definite integral from b to a of f(x) is: "; cout << ((deltax / 2) * ( f(a) + acc + f(b) ) ) << endl; }