Statsar Statistics Library

v1.0.1 for .NET

Product Guide



More Information...

Valid XHTML


Mersenne Twister Random Example (C#)

[C#]
/* COPYRIGHT(C), SIMPLEXAR SOFTWARE LIMITED, 2006-2008.
 * All rights reserved.
 *
 * Use of this copyright notice is precautionary only, and does not imply
 * publication or disclosure. The content of this work contains confidential
 * and proprietary information of Simplexar Software Limited. Any duplication,
 * modification, distribution, or disclosure in any form, in whole, or in part,
 * is strictly prohibited without express prior written permission.
 */

// Get namespaces.
using System;
using Simplexar.Statsar;
using Simplexar.Statsar.RandomNumbers;

// Start namespace.
namespace Simplexar.Examples.Statsar
{
    /// <summary>
    /// This example illustrates how to generate random deviates using
    /// the Mersenne twister random number generator algorithm.
    /// </summary>
    public static class Example
    {
        /// <summary>
        /// The application entry point.
        /// </summary>
        public static void Main()
        {
            try
            {
                RunExample();
            }
            catch(Exception exception)
            {
                Console.WriteLine(exception);
            }
            Console.WriteLine("Press ENTER to terminate.");
            Console.ReadLine();
        }

        private static void RunExample()
        {
            // Get a Mersenne twister generator implementing the MT19937
            // algorithm. MT19937 is the newer algorithm and is more commonly
            // used in random number generator applications.
            MersenneTwister random = RandomGenerators.GetMT19937();

            // Get a non-negative random number.
            Console.WriteLine(
                "Non-negative integer: {0}", random.Next());

            // Get a non-negative random number less than
            // the specified maximum.
            Console.WriteLine(
                "Non-negative integer less than 10: {0}", random.Next(10));

            // Get a random number greater or equal to the specified
            // minimum and less than the specified maximum.
            Console.WriteLine(
                "Integer greater or equal to 90 and less than 100: {0}",
                random.Next(90, 100));

            // Get a random number greater or equal to 0 and less than 1.
            Console.WriteLine(
                "Real number greater or equal to 0 and less than 1: {0}",
                random.NextDouble());

            // Fill an array of bytes with random numbers.
            Console.Write("Random bytes:");
            byte[] values = new byte[10];
            random.NextBytes(values);
            foreach(byte value in values)
            {
                Console.Write(" {0}", value);
            }
            Console.WriteLine();
        }
    }
}