C# Monte Carlo RNG Example

← All NMath Code Examples

 

using System;

using CenterSpace.NMath.Core;

namespace CenterSpace.NMath.Examples.CSharp
{
  /// <summary>
  /// A .NET example in C# showing how to calculate an approximation for Pi using a Monte
  /// Carlo method and the uniform random number generator class RandGenUniform.
  /// 
  /// Imagine a 2 x 2 square with corners at (1,1), (1,-1), (-1,-1) and (-1,1)
  /// and a unit circle, centered on the origin, inscribed within it. Generate 
  /// random points inside the square and let M be the number of points
  /// that fall within the unit circle and N be the total number of points
  /// generated. As the number N gets large, the quantity M/N should approximate the 
  /// ratio of the area of the circle to the square, which is pi/4. Hence, we can
  /// use the ratio 4*M/N to approximate Pi.
  /// </summary>
  class MonteCarloRNGExample
  {

    static void Main( string[] args )
    {
      // Construct a random number generator that generates random deviates
      // distributed uniformly over the interval [-1,1]
      var rng = new RandGenUniform( -1.0, 1.0 );

      // Well approximate pi to within 5 digits.
      double tolerance = 1e-5;

      double piApproximation = 0;
      int total = 0;
      int numInCircle = 0;
      double x, y; // Coordinates of the random point.

      // Generate random points until our approximation within
      // the desired tolerance.
      while ( Math.Abs( Math.PI - piApproximation ) > tolerance )
      {
        x = rng.Next();
        y = rng.Next();
        if ( x * x + y * y <= 1.0 ) // Is the point in the circle?
        {
          ++numInCircle;
        }
        ++total;
        piApproximation = 4.0 * ( (double) numInCircle / (double) total );
      }

      Console.WriteLine();

      Console.WriteLine( "Pi calculated to within {0} digits with {1} random points.",
        -Math.Log10( tolerance ), total );
      Console.WriteLine( "Approximated Pi = {0}", piApproximation );

      Console.WriteLine();
      Console.WriteLine( "Press Enter Key" );
      Console.Read();
    }
  }// class

}// namespace

← All NMath Code Examples
Top