Skip to content

Instantly share code, notes, and snippets.

@ovr
Created June 17, 2014 03:40
Show Gist options
  • Save ovr/a8e41d1578fa8d8d0f40 to your computer and use it in GitHub Desktop.
Save ovr/a8e41d1578fa8d8d0f40 to your computer and use it in GitHub Desktop.
#include "hsTimer.h"
#include <stdlib.h>
#include <iostream>
#include <tchar.h>
#include <math.h>
using namespace std;
using namespace MobyDisk;
class LinearCongruentRnd {
private:
__int64 state;
public:
LinearCongruentRnd(int start) {
state = start;
}
unsigned int nextInt()
{
state = state*7919 + 104729;
return static_cast<unsigned int>(state & 0xFFFFFFFF);
}
double nextDouble() {
return (double)nextInt()/UINT_MAX;
}
};
void calculatePI()
{
double pi = 0; // Accumulated value of pi
double ms = 0; // Elapsed time
int count = 0; // Number of iterations run
static const int testTimeMS = 10000; // Run the test for 10 seconds
LinearCongruentRnd rand(12345);
hsTimer::init();
hsTime start = hsTimer::getTime();
do
{
// Random sampling method similar to the buffon needle experiment
double x,y; // Random coordinates -0.5...0.5
int inside=0; // Number of hits inside the circle
int outside=0; // Number of hits outside the circle
// Run a bunch of samples
for (int samples=0; samples<10000000; samples++)
{
// Generate coordinates
x = rand.nextDouble() - 0.5;
y = rand.nextDouble() - 0.5;
// Inside the circle?
if (x*x+y*y<0.25)
inside++;
else
outside++;
}
// Calculate the value of pi
double new_pi = 4*static_cast<double>(inside)/(inside+outside);
// Accumulate it
pi += new_pi;
count++;
// How long did this take?
ms = hsTimer::getElapsed(start);
} while (ms < testTimeMS);
// PI is
cout << "PI = " << pi/count << endl;
cout << "Iterations ran = " << count << endl;
cout << "Time = " << ms << " ms" << endl;
cout << "Iterations per second = " << 1000*count/ms << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
calculatePI();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment