MCPI - int successes = 0; for(int i = 0; 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 DocumentRight 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 &lt; iterations; i++) { // Here's our trick: we know upper &amp; 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&lt;double&gt;(RAND_MAX); double y = rand() / static_cast&lt;double&gt;(RAND_MAX); if(inUnitCircle(x,y)) successes++; } // We know the result is pi/4. double result = successes / static_cast&lt;double&gt;(iterations); return 4 * result; } int main() { srand(time(0)); int iter; cout &lt;&lt; &quot;Iterations: &quot;; cin &gt;&gt; iter; assert(cin); cout &lt;&lt; &quot;PI estimate: &quot; &lt;&lt; estimate_pi(iter) &lt;&lt; endl; }...
View Full Document

Page1 / 2

MCPI - int successes = 0; for(int i = 0; i &amp;amp;lt;...

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