// Author: Mark Lingle // Modified: Volker Crede // // Project 11 // 4-1-08 #include #include using namespace std; class IntegralCalculator // main integration class { public: IntegralCalculator (double aIntegrandFunction(double)) { iIntegrandFunction = aIntegrandFunction; } void setNumberOfIntervals(const int aNumberOfIntervals)p; int numberOfIntervals(); // This function calculates the integrals using rectangles void integrate(double aLeftLimit, double aRightLimit, int aNumberOfIntervals, double integrand(double)) { double dx = (aRightLimit - aLeftLimit) / aNumberOfIntervals; double x = 0; double sum = 0; for (int loop = 0; loop < aNumberOfIntervals; loop++) { sum += integrand(x); x+= dx; } } // input data void readInputData() { cout << "This program will integrate the function f(x) = x*x for any limits you choose." << endl; cout << "Input the lower and upper limits of your integral: "; cin >> aLeftLimit >> aRightLimit; cout << "Input the number of intervals: "; cin >> aNumberOfIntervals; } // Displays results void print() { cout << "The answer is " << aResult << endl << endl; } void SimpsonRule() // calculates integral using Simpson 3-point rule { double w = (aRightLimit - aLeftLimit) / aNumberOfIntervals; double sum = 0; for (int i = 0; i < aNumberOfIntervals - 1; i++) { sum += iIntegrandFunction(aLeftLimit + i*w) + 4*iIntegrandFunction(aLeftLimit+ w*(i+0.5)) + iIntegrandFunction(aLeftLimit + (i + 1)*w); } aResult = (w/6.0)*sum; } private: int aNumberOfIntervals; // Number of intervals double aLeftLimit, aRightLimit, aResult; // declares variables double (*iIntegrandFunction) (double); // function to be integrated }; //Function that is being integrated. f(x)=x^2 double square(double aX) { return aX*aX; } int main(){ char ch = 'y'; while (ch == 'y' || ch == 'Y') // Program stays in loop till user // terminates by inputing "n/N." { IntegralCalculator IC1(square); // create the calculator IC1.readInputData(); // get user input IC1.SimpsonRule(); // INTEGRATE! IC1.print(); // output result cout << "This program was written and compiled by Mark Lingle for PHZ4151C." << endl; cout << "Would you like to run it again?" << endl; cout << "Please enter y/Y for yes or n/N for no." << endl; cin >> ch; } }