Skip to content
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions chapters/monte_carlo/code/c#/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System;

namespace MonteCarlo
{
class Program
{
private static Random random = new Random(47);
private const int radius = 1;


public static void Main(string[] args)
{
double piEstimate = MonteCarloMethod(1000000);

Console.WriteLine("Pi estimate = {0}", piEstimate);
Console.WriteLine("Pi error = {0}", 100 * (Math.Abs(Math.PI - piEstimate)) / Math.PI);

Console.ReadLine();
}


private static double MonteCarloMethod(int samples)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would move this to a separate file called MonteCarlo with the class MonteCarlo and rename the method into Run(), since that's the way all other C# implementations work (look here for reference https://www.algorithm-archive.org/chapters/computational_geometry/gift_wrapping/jarvis_march/jarvis_march.html).

{
int piCount = 0;

for (int i = 0; i < samples; i++)
{
var randomX = random.NextDouble() * radius;
var randomY = random.NextDouble() * radius;

if (IsInCircle(randomX, randomY))
{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is just a single line, you don't need the curly braces. I would remove them, what do you think?

piCount++;
}
}

return 4 * piCount / (double)samples;
}


private static bool IsInCircle(double x, double y)
{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here you can use => sine you just have a single line in the method. So the method would roughly look like this

private static bool IsInCircle(double x, double y) => x * x + y * y < radius * radius;

It's also just a suggestion and I would like to hear your input.

return x * x + y * y < radius * radius;
}
}
}