C# Random Number 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 normal distribution,
  /// using the class RandGenNormal, and place them in a histogram.
  /// </summary>
  class NormalRNGExample
  {

    static void Main( string[] args )
    {
      double mean = 70.0;
      double variance = 10.0;

      // Create a default generator. The default generator will generate 
      // random numbers from a normal distribution with a specified mean
      // and variance.
      var normalRng = new RandGenNormal( mean, variance );

      // Now construct a vector of random numbers using this generator.
      int numRandDeviates = 200;
      var randomVec = new DoubleVector( numRandDeviates, normalRng );

      // Create a histogram with equal sized bins for the random numbers.
      int numBins = 20;
      var h = new Histogram( numBins, randomVec );

      Console.WriteLine();

      // Print out the histogram in a "stem leaf" format.
      Console.WriteLine( "{0} random deviates from a normal({1},{2}) distribution:",
        numRandDeviates, mean, variance );
      Console.WriteLine( h.StemLeaf() );

      // Change the mean and variance for generator and check the mean and  
      // variance of the generated deviates.
      normalRng.Mean = -2.0;
      normalRng.Variance = 1.0;
      randomVec = new DoubleVector( 1000, normalRng );

      double meanOfDeviates = NMathFunctions.Mean( randomVec );
      Console.WriteLine( "Distribution mean = {0}, mean of deviates = {1}",
        normalRng.Mean, meanOfDeviates );

      double varianceOfDeviates = NMathFunctions.Variance( randomVec );
      Console.WriteLine( "Distribution variance = {0}, variance of deviates = {1}",
        normalRng.Variance, varianceOfDeviates );

      // Replace the vectors contents with new random numbers
      randomVec.Transform( new Func<double>( normalRng.NextDouble ) );

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

}// namespace

← All NMath Code Examples
Top