Mega Code Archive

 
Categories / C# / Date Time
 

Estimates pi by throwing points into a square Use to compare execution times

/* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // // CalcPi.cs -- Estimates pi by throwing points into a square. Use to //              compare execution times. // //              Compile this program with the following command line: //                  C:>csc CalcPi.cs // namespace CalcPi {     using System;     public class CalcPi     {         static void Main ()         {             const int throws = 10000000;             DateTime now = DateTime.Now;             Random rand = new Random ((int) now.Millisecond);             int Inside = 0;             for (int i = 0; i < throws; ++i)             {                 double cx = rand.NextDouble();                 double cy = rand.NextDouble();                 double distance = Math.Sqrt ((cx * cx) + (cy * cy));                 if (distance < 1.0)                     ++Inside;             }             double pi = 4 * (double) Inside / (double) throws;             DateTime End = DateTime.Now;             TimeSpan Diff = End - now;             Console.WriteLine ("pi = " + pi);             Console.WriteLine ("Milliseconds = " + Diff.TotalMilliseconds);         }     } }