Skip to content

Instantly share code, notes, and snippets.

@m-khooryani
Last active June 10, 2020 06:57
Show Gist options
  • Save m-khooryani/d62a4c3b7761d5269e487a68a70c905c to your computer and use it in GitHub Desktop.
Save m-khooryani/d62a4c3b7761d5269e487a68a70c905c to your computer and use it in GitHub Desktop.
calculate Pi using Monte Carlo
This problem was asked by Google.
The area of a circle is defined as πr^2.
Estimate π to 3 decimal places using a Monte Carlo method.
Hint: The basic equation of a circle is x2 + y2 = r2.
class Program
{
static void Main(string[] args)
{
Tuple<long, double> tuple = CalculatePI(new Random(0));
var points = tuple.Item1;
var pi = tuple.Item2;
Console.WriteLine($"PI: {pi} using Monte Carlo method with {points} points.");
}
private static Tuple<long, double> CalculatePI(Random rand)
{
long n = 0L;
long insidePoints = 0L;
do
{
n++;
double x = rand.NextDouble();
double y = rand.NextDouble();
if (x * x + y * y <= 1.0)
{
insidePoints++;
}
} while (Math.Abs(Math.PI - insidePoints * 4.0 / n) > 1e-3);
return new Tuple<long, double>(n, insidePoints * 4.0 / n);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment