C# Vectorized 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 generate random numbers from a stream.
  /// </summary>
  class VectorizedRNGExample
  {

    static void Main( string[] args )
    {
      // Unlike scalar-type generators whose output is a successive random number, vector 
      // generators produce a vector of n successive random numbers from a given 
      // distribution. Vector type random number generators will generally perform
      // better than scalar ones because overhead expense of a function call
      // is comparable to the total time required for computation. 

      // A stream is constructed from an optional seed, and an optional enumerated value specifying which
      // algorithm to use for generating random numbers uniformly distributed in the interval [0, 1].
      int seed = 0x345;
      var stream = new RandomNumberStream( seed, RandomNumberStream.BasicRandGenType.MersenneTwister );

      // NMath provides distribution classes for many continuous and discrete distributions, each with 
      // their own distribution parameters.
      double mean = 1.0;
      double sigma = 1.0;
      var dist = new DoubleRandomGaussianDistribution( mean, sigma );

      // You can use a stream and distribution to fill an array. 
      int n = 100;
      int start = 0;
      var a = new double[n];
      dist.Fill( stream, a, start, n );

      // Or to fill a new vector or matrix.
      stream.Reset( seed );
      var v = new DoubleVector( n, stream, dist );

      Console.WriteLine();

      // Display a histogram.
      int numbins = 10;
      var hist = new Histogram( numbins, v );
      Console.WriteLine( hist );

      // If you want the performance of a vectorized random number generator, but still need to access the 
      // random deviates sequentially, NMath provides class RandomNumbers, which uses a stream to
      // buffer the random numbers internally.
      int bufferSize = 100;
      var rnd = new RandomNumbers<double, DoubleRandomGaussianDistribution>( seed, dist, bufferSize );
      for ( int i = 0; i < 10; i++ )
      {
        Console.WriteLine( "Next() = {0}", (double) rnd.Next() );
      }

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

  } // class

} // namespace

← All NMath Code Examples
Top