// // Example 7.7. Program to estimate the area under a curve // using the dartboard method // #include #include #include "randDef.h" using namespace std; const int NUMDARTS = 1000; // number of darts to throw const float SMALLEST_X = 0.0; // smallest x value const float LARGEST_X = 2.0; // largest x value const float MAX_Y = 1.5; // upper bound of y values int main() { int countHitsBelow(); int numHitsBelow; // number of darts below curve float areaOfRectangle; // area of rectangular dartboard float estimatedArea; // estimated area under curve seedRand(); numHitsBelow = countHitsBelow(); areaOfRectangle = (LARGEST_X - SMALLEST_X) * MAX_Y; estimatedArea = areaOfRectangle * numHitsBelow / NUMDARTS; cout << "Estimated area under curve from " << SMALLEST_X << " to " << LARGEST_X << " is " << estimatedArea << endl; return 0; } // // Function to throw darts and return number of hits below curve // Pre: none // Post: The number of darts hitting below curve was returned. // int countHitsBelow() { float f(float x); int numHitsBelow = 0; // number of darts below curve float randomX; // random x between SMALLEST_X & LARGEST_X float randomY; // random y between 0 & MAX_Y float fOfX; // f(x) for (int i = 0; i < NUMDARTS; ++i) { randomX = randomDoubleRange(SMALLEST_X, LARGEST_X); randomY = randomDoubleRange(0, MAX_Y); fOfX = f(randomX); if (randomY < fOfX) ++numHitsBelow; } return numHitsBelow; } // // A mathematical function // Pre: x is a floating point number. // Post: The square root of ((cos(x))^2 + 1) was returned. // float f(float x) { return (sqrt(cos(x) * cos(x) + 1)); }