SOURCE FILE: 7.07AreaEstimator.cpp
//
// Example 7.7. Program to estimate the area under a curve
// using the dartboard method
//
#include <iostream.h>
#include <math.h>
#include "RandDef.h"
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(void)
{
int CountHitsBelow(void);
int NumHitsBelow; // number of darts below curve
float AreaOfRectangle, // area of rectangular dartboard
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(void)
{
float f(float x);
int NumHitsBelow = 0; // number of darts below curve
float randomX, // random x between SMALLEST_X & LARGEST_X
randomY, // random y between 0 & MaxY
f_of_x; // f(x)
for (int i = 0; i < NUMDARTS; i++)
{
randomX = random_double_range(SMALLEST_X, LARGEST_X);
randomY = random_double_range(0, MAX_Y);
f_of_x = f(randomX);
if (randomY < f_of_x)
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));
}