/********************************************************************* Copyright (C) : University of Michigan Project: ENG101/200 - Class example File: randomIntegrate.cpp Purpose: Integrates a function by random sampling Compiler: g++ Programmer: Alex Bielajew Start Date: 09/28/10 *********************************************************************/ //File: randomIntegrate.cpp #include #include #include // Need for rand() and srand() #include // Need for exp(), the exponential function // and abs(), the absolute value function using namespace std; /* Define a conversion function that converts the int returned from rand() to a double between 0.0 and 1.0 inclusive */ #define MYRAND (static_cast(rand())/RAND_MAX) int main(void) { int nDarts = 100000000, under = 0; double Ans = 1 - exp(-1); for(int i = 1; i <= nDarts; i = i + 1) { double xDart = MYRAND; double yDart = MYRAND; if (yDart <= exp(-xDart)) under = under + 1; if (0 == i%1000000) // Every million times { double ans = static_cast(under)/i; cout << setiosflags(ios::fixed) << setprecision(8) << "#" << setw(10) << i << ": I = " << setw(10) << ans << ", Delta = " << abs(1 - exp(-1) - ans) << "\n"; } } return 0; }