MCPI - int successes = 0 for(int i = 0 i< iterations i...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
#include <iostream> #include <cstdlib> #include <cassert> using namespace std; bool inUnitCircle(double x, double y) { // Is the distance to (0,0) < 1? // sqrt((x-0)^2 + (y-0)^2) < 1 // equivalently, x*x + y*y < 1 return x*x + y*y < 1; // Typically when doing Monte-Carlo integration, we'd answer this question more directly: // return y < f(x); // where f is the function we're trying to integrate. // Some trig tells us that what we're actually doing here is: // return y < sin(acos(x)) // Why aren't we doing this? Well, acos(-1) = pi. So. .. assume we don't have it! } double estimate_pi(int iterations) { // We're going to integrate sin(acos(x)) from 0 to 1. // (positive half of the unit circle)
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: int successes = 0; for(int i = 0; i < iterations; i++) { // Here's our trick: we know upper & lower bounds of our function between 0 and 1. // And we know the area of the rectangle these bounds give us: it's 1. // Pick a point in this rectangle. double x = rand() / static_cast<double>(RAND_MAX); double y = rand() / static_cast<double>(RAND_MAX); if(inUnitCircle(x,y)) successes++; } // We know the result is pi/4. double result = successes / static_cast<double>(iterations); return 4 * result; } int main() { srand(time(0)); int iter; cout << "Iterations: "; cin >> iter; assert(cin); cout << "PI estimate: " << estimate_pi(iter) << endl; }...
View Full Document

{[ snackBarMessage ]}

Page1 / 2

MCPI - int successes = 0 for(int i = 0 i< iterations i...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online