Skip to content

Instantly share code, notes, and snippets.

@ovr
Created June 17, 2014 03:41
Show Gist options
  • Save ovr/5a7ab7b3361b6e4069bd to your computer and use it in GitHub Desktop.
Save ovr/5a7ab7b3361b6e4069bd to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Text;
namespace test_cs20
{
class Program
{
static void calculatePI()
{
double pi = 0; // Accumulated value of pi
double ms = 0; // Elapsed time
int count = 0; // Number of iterations run
const int testTimeMS = 30000; // Run the test for 10 seconds
LinearCongruentRnd rand = new LinearCongruentRnd(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.0*inside/(inside+outside);
// Accumulate it
pi += new_pi;
count++;
// How long did this take?
ms = hsTimer.getElapsed(start);
} while (ms < testTimeMS);
// PI is
System.Console.WriteLine("PI = " + pi/count);
System.Console.WriteLine("Iterations ran = " + count);
System.Console.WriteLine("Time = " + ms + " ms");
System.Console.WriteLine("Iterations per second = " + 1000*count/ms);
}
static void Main(string[] args)
{
calculatePI();
}
}
public struct hsTime
{
internal long ticks;
internal hsTime(long v)
{
ticks = v;
}
}
class hsTimer
{
public static void init()
{
}
public static hsTime getTime()
{
return new hsTime(System.DateTime.Now.Ticks);
}
public static double getElapsed(hsTime start)
{
long ticks = System.DateTime.Now.Ticks - start.ticks;
return ticks/(double)System.TimeSpan.TicksPerMillisecond;
}
}
class LinearCongruentRnd
{
private System.UInt64 state;
public LinearCongruentRnd(System.UInt64 start)
{
state = start;
}
public System.UInt32 nextInt()
{
state = state*7919 + 104729;
return (System.UInt32)(state & 0xFFFFFFFF);
}
public double nextDouble()
{
return (double)nextInt()/0xFFFFFFFF;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment