csaki

Another way to calculate PI

Mar 4th, 2014
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.11 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace CalculatePi
  7. {
  8.     struct Point
  9.     {
  10.         public double x;
  11.         public double y;
  12.     }
  13.  
  14.     class Program
  15.     {
  16.  
  17.         static void Main(string[] args)
  18.         {
  19.             var startdate = DateTime.Now;
  20.             double n = 20000000;
  21.             Point p;
  22.             Random rand = new Random();
  23.             int count = 0;
  24.            
  25.             for (int i = 0; i < n; i++)
  26.             {
  27.                 p.x = rand.NextDouble() * 2 - 1;
  28.                 p.y = rand.NextDouble() * 2 - 1;
  29.                 if (IsInCircle(p)) count++;
  30.             }
  31.             var enddate = DateTime.Now;
  32.             Console.WriteLine("In case of {0} numbers, result came in {1} seconds", n, (enddate-startdate).TotalSeconds);
  33.             Console.WriteLine("Result is: " + 4.0 * count / n);
  34.             Console.WriteLine("Math.PI: " + Math.PI);
  35.             Console.ReadLine();
  36.         }
  37.  
  38.         static bool IsInCircle(Point p)
  39.         {
  40.             return Math.Sqrt(p.x * p.x + p.y * p.y) < 1;
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment