Advertisement
vencinachev

MonteCarloPI

Apr 20th, 2021
1,028
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.02 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Svetlina
  8. {
  9.     class Program
  10.     {
  11.         public static double MonteCarloPI(int n)
  12.         {
  13.             Random rand = new Random();
  14.             int pointsIn = 0;
  15.             for (int i = 0; i < n; i++)
  16.             {
  17.                 double x = rand.NextDouble();
  18.                 double y = rand.NextDouble();
  19.                 if (Math.Sqrt(x * x + y * y) <= 1)
  20.                 {
  21.                     pointsIn++;
  22.                 }
  23.             }
  24.             return 4.0 * (double)pointsIn / n;
  25.         }
  26.         static void Main(string[] args)
  27.         {
  28.             Console.WriteLine("PI = " + MonteCarloPI(10));
  29.             Console.WriteLine("PI = " + MonteCarloPI(100));
  30.             Console.WriteLine("PI = " + MonteCarloPI(10000));
  31.             Console.WriteLine("PI = " + MonteCarloPI(1000000));
  32.             Console.WriteLine("PI = " + MonteCarloPI(100000000));
  33.         }
  34.     }
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement