diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 50199d0d4..0fffc591a 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -40,3 +40,4 @@ GuyPozner
William Boyles
+sanstorik diff --git a/chapters/monte_carlo/code/csharp/MonteCarlo.cs b/chapters/monte_carlo/code/csharp/MonteCarlo.cs new file mode 100644 index 000000000..390f95d5f --- /dev/null +++ b/chapters/monte_carlo/code/csharp/MonteCarlo.cs @@ -0,0 +1,40 @@ +// submitted by vitalii shvetsov (@sanstorik) +using System; +using System.Collections.Generic; +using System.Text; + +namespace MonteCarlo +{ + class MonteCarlo + { + private static Random random = new Random(47); + private int Radius { get; set; } + private int Samples { get; set; } + + + public MonteCarlo(int radius = 1, int samples = 1000000) + { + Radius = radius; + Samples = samples; + } + + + public double Run() + { + int piCount = 0; + + for (int i = 0; i < Samples; i++) + { + var randomX = random.NextDouble() * Radius; + var randomY = random.NextDouble() * Radius; + + if (IsInCircle(randomX, randomY)) piCount++; + } + + return 4 * piCount / (double)Samples; + } + + + private bool IsInCircle(double x, double y) => x * x + y * y < Radius * Radius; + } +} diff --git a/chapters/monte_carlo/code/csharp/Program.cs b/chapters/monte_carlo/code/csharp/Program.cs new file mode 100644 index 000000000..576d3e3fd --- /dev/null +++ b/chapters/monte_carlo/code/csharp/Program.cs @@ -0,0 +1,18 @@ +using System; + +// submitted by vitalii shvetsov (@sanstorik) +namespace MonteCarlo +{ + class Program + { + public static void Main(string[] args) + { + double piEstimate = new MonteCarlo(1, 1000000).Run(); + + Console.WriteLine("Pi estimate = {0}", piEstimate); + Console.WriteLine("Pi error = {0}", 100 * (Math.Abs(Math.PI - piEstimate)) / Math.PI); + + Console.ReadLine(); + } + } +} diff --git a/chapters/monte_carlo/monte_carlo.md b/chapters/monte_carlo/monte_carlo.md index e777bdaa4..6171afa18 100644 --- a/chapters/monte_carlo/monte_carlo.md +++ b/chapters/monte_carlo/monte_carlo.md @@ -59,8 +59,11 @@ each point is tested to see whether it's in the circle or not: [import:13-15, lang:"java"](code/java/MonteCarlo.java) {% sample lang="swift" %} [import:21-25, lang:"swift"](code/swift/monte_carlo.swift) +{% sample lang="csharp" %} +[import:37-39, lang:"csharp"](code/csharp/MonteCarlo.cs) {% endmethod %} + If it's in the circle, we increase an internal count by one, and in the end, $$ @@ -123,6 +126,8 @@ Feel free to submit your version via pull request, and thanks for reading! {% sample lang="swift" %} ### Swift [import, lang:"swift"](code/swift/monte_carlo.swift) +### CSharp +[import, lang:"csharp"](code/csharp/MonteCarlo.cs) {% endmethod %}