Having troubles with Randomness

I am new to these boards so not sure if I should post code snippets or how you guys handle things. Basically the issue can easily be seen here:

http://www.thecodeproject.com/csharp/CsharpMersenneTwister.asp

If you don't have an account there you can just download the binary called the demo.

When you run this simple dice program you can see that it always has the same results. Do so by running it, memorizing the number of rolls for each number at the bottom right, close the program, and run it again and perform the same action.

Given that these results in that one iteration are seemingly random. I want to create a program that has random results dependently of each trail. If I get the same sequence of randomness for each time I run the program then I won't learn anything past that one sequence. I think this has something to do with creating random seeds, but creating random seeds is just as dependent on being able to get a random number.

I had no better luck for good randomness using the Random class given by .NET, but will take any suggestions.

Anything



Answer this question

Having troubles with Randomness

  • Vadim_Luk

    It all depends on your seed. The Random class is good to generate random numbers, but you must supply a good seed.

    If you want to the the R250/521 random qeuence generator you can take a look to this and this.

    A implementatino for the Mersenne Twister you can use this code.


    public sealed class R250_521 {
    private int r250_index;
    private int r521_index;
    private int r250_buffer[250];
    private int r521_buffer[521];

    public R250_521() {
    Random r = new Random();
    int i = 521;
    int mask1 = 1;
    int mask2 = 0xFFFFFFFF;

    while (i-- > 250) {
    r521_bufferIdea = r.Next();
    }
    while (i-- > 31) {
    r250_bufferIdea = r.Next();
    r521_bufferIdea = r.Next();
    }

    /*
    Establish linear independence of the bit columns
    by setting the diagonal bits and clearing all bits above
    */
    while (i-- > 0) {
    r250_bufferIdea = (r.Next() | mask1) & mask2;
    r521_bufferIdea = (r.Next() | mask1) & mask2;
    mask2 ^= mask1;
    mask1 >>= 1;
    }
    r250_buffer[0] = mask1;
    r521_buffer[0] = mask2;
    r250_index = 0;
    r521_index = 0;
    }

    public int random() {
    int i1 = r250_index;
    int i2 = r521_index;

    int j1 = i1 - (250-103);
    if (j1 < 0)
    j1 = i1 + 103;
    int j2 = i2 - (521-168);
    if (j2 < 0)
    j2 = i2 + 168;

    int r = r250_buffer[j1] ^ r250_buffer[i1];
    r250_buffer[i1] = r;
    int s = r521_buffer[j2] ^ r521_buffer[i2];
    r521_buffer[i2] = s;

    i1 = (i1 != 249) (i1 + 1) : 0;
    r250_index = i1;
    i2 = (i2 != 521) (i2 + 1) : 0;
    r521_index = i2;

    return r ^ s;
    }
    }




  • Ed_Zero

    An other MT implementation can be found in the Netron project, here is the code:


    using System;

    namespace Netron.GraphLib.Maths
    {
    /////////////////////////////////////////////////////////////////////////////
    // C# Version Copyright (c) 2003 CenterSpace Software, LLC //
    // //
    // This code is free software under the Artistic license. //
    // //
    // CenterSpace Software //
    // 2098 NW Myrtlewood Way //
    // Corvallis, Oregon, 97330 //
    // USA //
    // http://www.centerspace.net //
    /////////////////////////////////////////////////////////////////////////////


    /*
    A C-program for MT19937, with initialization improved 2002/1/26.
    Coded by Takuji Nishimura and Makoto Matsumoto.

    Before using, initialize the state by using init_genrand(seed)
    or init_by_array(init_key, key_length).

    Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

    3. The names of its contributors may not be used to endorse or promote
    products derived from this software without specific prior written
    permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


    Any feedback is very welcome.
    http://www.math.keio.ac.jp/matumoto/emt.html
    email: matumoto@math.keio.ac.jp
    */


    ///
    /// Class MersenneTwister generates random numbers from a uniform distribution using
    /// the Mersenne Twister algorithm.
    ///
    /// Caution: MT is for MonteCarlo, and is NOT SECURE for CRYPTOGRAPHY
    /// as it is.
    [Serializable()]public class MersenneTwister
    {
    #region Constants -------------------------------------------------------

    // Period parameters.
    private const int N = 624;
    private const int M = 397;
    private const uint MATRIX_A = 0x9908b0dfU; // constant NetronVector a
    private const uint UPPER_MASK = 0x80000000U; // most significant w-r bits
    private const uint LOWER_MASK = 0x7fffffffU; // least significant r bits
    private const int MAX_RAND_INT = 0x7fffffff;

    #endregion Constants

    #region Instance Variables ----------------------------------------------

    // mag01[x] = x * MATRIX_A for x=0,1
    private uint[] mag01 = {0x0U, MATRIX_A};

    // the array for the state NetronVector
    private uint[] mt = new uintNo;

    // mti==N+1 means mtNo is not initialized
    private int mti = N+1;

    #endregion Instance Variables

    #region Constructors ----------------------------------------------------

    ///
    /// Creates a random number generator using the time of day in milliseconds as
    /// the seed.
    ///
    public MersenneTwister()
    {
    init_genrand( (uint)DateTime.Now.Millisecond );
    }

    ///
    /// Creates a random number generator initialized with the given seed.
    ///
    /// The seed.
    public MersenneTwister( int seed )
    {
    init_genrand( (uint)seed );
    }

    ///
    /// Creates a random number generator initialized with the given array.
    ///
    /// The array for initializing keys.
    public MersenneTwister( int[] init )
    {
    uint[] initArray = new uint[init.Length];
    for ( int i = 0; i < init.Length; ++i )
    initArrayIdea = (uint)initIdea;

    init_by_array( initArray, (uint)initArray.Length );
    }

    #endregion Constructors

    #region Properties ------------------------------------------------------

    ///
    /// Gets the maximum random integer value. All random integers generated
    /// by instances of this class are less than or equal to this value. This
    /// value is 0x7fffffff (2,147,483,647).
    ///
    public static int MaxRandomInt
    {
    get
    {
    return 0x7fffffff;
    }
    }

    #endregion Properties

    #region Member Functions ------------------------------------------------

    ///
    /// Returns a random integer greater than or equal to zero and
    /// less than or equal to MaxRandomInt.
    ///
    /// The next random integer.
    public int Next()
    {
    return genrand_int31();
    }

    ///
    /// Returns a positive random integer less than the specified maximum.
    ///
    /// The maximum value. Must be greater than zero.
    /// A positive random integer less than or equal to maxValue.
    public int Next( int maxValue )
    {
    return Next( 0, maxValue );
    }

    ///
    /// Returns a random integer within the specified range.
    ///
    /// The lower bound.
    /// The upper bound.
    /// A random integer greater than or equal to minValue, and less than
    /// or equal to maxValue.
    public int Next( int minValue, int maxValue )
    {
    if ( minValue > maxValue )
    {
    int tmp = maxValue;
    maxValue = minValue;
    minValue = tmp;
    }

    return (int)( Math.Floor((maxValue-minValue+1)*genrand_real1() + minValue) );
    }

    ///
    /// Returns a random number between 0.0 and 1.0.
    ///
    /// A single-precision floating point number greater than or equal to 0.0,
    /// and less than 1.0.
    public float NextFloat()
    {
    return (float) genrand_real2();
    }

    ///
    /// Returns a random number greater than or equal to zero, and either strictly
    /// less than one, or less than or equal to one, depending on the value of the
    /// given boolean parameter.
    ///
    ///
    /// If true, the random number returned will be
    /// less than or equal to one; otherwise, the random number returned will
    /// be strictly less than one.
    ///
    ///
    /// If includeOne is true, this method returns a
    /// single-precision random number greater than or equal to zero, and less
    /// than or equal to one. If includeOne is false, this method
    /// returns a single-precision random number greater than or equal to zero and
    /// strictly less than one.
    ///
    public float NextFloat( bool includeOne )
    {
    if ( includeOne )
    {
    return (float) genrand_real1();
    }
    return (float) genrand_real2();
    }

    ///
    /// Returns a random number greater than 0.0 and less than 1.0.
    ///
    /// A random number greater than 0.0 and less than 1.0.
    public float NextFloatPositive()
    {
    return (float) genrand_real3();
    }

    ///
    /// Returns a random number between 0.0 and 1.0.
    ///
    /// A double-precision floating point number greater than or equal to 0.0,
    /// and less than 1.0.
    public double NextDouble()
    {
    return genrand_real2();
    }

    ///
    /// Returns a random number greater than or equal to zero, and either strictly
    /// less than one, or less than or equal to one, depending on the value of the
    /// given boolean parameter.
    ///
    ///
    /// If true, the random number returned will be
    /// less than or equal to one; otherwise, the random number returned will
    /// be strictly less than one.
    ///
    ///
    /// If includeOne is true, this method returns a
    /// single-precision random number greater than or equal to zero, and less
    /// than or equal to one. If includeOne is false, this method
    /// returns a single-precision random number greater than or equal to zero and
    /// strictly less than one.
    ///
    public double NextDouble( bool includeOne )
    {
    if ( includeOne )
    {
    return genrand_real1();
    }
    return genrand_real2();
    }

    ///
    /// Returns a random number greater than 0.0 and less than 1.0.
    ///
    /// A random number greater than 0.0 and less than 1.0.
    public double NextDoublePositive()
    {
    return genrand_real3();
    }

    ///
    /// Generates a random number on [0,1) with 53-bit resolution.
    ///
    /// A random number on [0,1) with 53-bit resolution
    public double Next53BitRes()
    {
    return genrand_res53();
    }

    ///
    /// Reinitializes the random number generator using the time of day in
    /// milliseconds as the seed.
    ///
    public void Initialize()
    {
    init_genrand( (uint)DateTime.Now.Millisecond );
    }


    ///
    /// Reinitializes the random number generator with the given seed.
    ///
    /// The seed.
    public void Initialize( int seed )
    {
    init_genrand( (uint)seed );
    }

    ///
    /// Reinitializes the random number generator with the given array.
    ///
    /// The array for initializing keys.
    public void Initialize( int[] init )
    {
    uint[] initArray = new uint[init.Length];
    for ( int i = 0; i < init.Length; ++i )
    initArrayIdea = (uint)initIdea;

    init_by_array( initArray, (uint)initArray.Length );
    }


    #region Methods ported from C -------------------------------------------

    // initializes mtNo with a seed
    private void init_genrand( uint s)
    {
    mt[0]= s & 0xffffffffU;
    for (mti=1; mti {
    mt[mti] =
    (uint)(1812433253U * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
    // See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier.
    // In the previous versions, MSBs of the seed affect
    // only MSBs of the array mt[].
    // 2002/01/09 modified by Makoto Matsumoto
    mt[mti] &= 0xffffffffU;
    // for >32 bit machines
    }
    }

    // initialize by an array with array-length
    // init_key is the array for initializing keys
    // key_length is its length
    private void init_by_array(uint[] init_key, uint key_length)
    {
    int i, j, k;
    init_genrand(19650218U);
    i=1; j=0;
    k = (int)(N>key_length N : key_length);
    for (; k>0; k--)
    {
    mtIdea = (uint)((uint)(mtIdea ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525U)) + init_key[j] + j); /* non linear */
    mtIdea &= 0xffffffffU; // for WORDSIZE > 32 machines
    i++; j++;
    if (i>=N) { mt[0] = mt[N-1]; i=1; }
    if (j>=key_length) j=0;
    }
    for (k=N-1; k>0; k--)
    {
    mtIdea = (uint)((uint)(mtIdea ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941U))- i); /* non linear */
    mtIdea &= 0xffffffffU; // for WORDSIZE > 32 machines
    i++;
    if (i>=N) { mt[0] = mt[N-1]; i=1; }
    }

    mt[0] = 0x80000000U; // MSB is 1; assuring non-zero initial array
    }

    // generates a random number on [0,0xffffffff]-interval
    uint genrand_int32()
    {
    uint y;
    if (mti >= N)
    { /* generate N words at one time */
    int kk;

    if (mti == N+1) /* if init_genrand() has not been called, */
    init_genrand(5489U); /* a default initial seed is used */

    for (kk=0;kk {
    y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
    mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1U];
    }
    for (;kk {
    y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
    mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1U];
    }
    y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
    mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1U];

    mti = 0;
    }

    y = mt[mti++];

    // Tempering
    y ^= (y >> 11);
    y ^= (y << 7) & 0x9d2c5680U;
    y ^= (y << 15) & 0xefc60000U;
    y ^= (y >> 18);

    return y;
    }

    // generates a random number on [0,0x7fffffff]-interval
    private int genrand_int31()
    {
    return (int)(genrand_int32()>>1);
    }

    // generates a random number on [0,1]-real-interval
    double genrand_real1()
    {
    return genrand_int32()*(1.0/4294967295.0);
    // divided by 2^32-1
    }

    // generates a random number on [0,1)-real-interval
    double genrand_real2()
    {
    return genrand_int32()*(1.0/4294967296.0);
    // divided by 2^32
    }

    // generates a random number on (0,1)-real-interval
    double genrand_real3()
    {
    return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0);
    // divided by 2^32
    }

    // generates a random number on [0,1) with 53-bit resolution
    double genrand_res53()
    {
    uint a=genrand_int32()>>5, b=genrand_int32()>>6;
    return(a*67108864.0+b)*(1.0/9007199254740992.0);
    }
    // These real versions are due to Isaku Wada, 2002/01/09 added

    #endregion Methods ported from C

    #endregion Member Functions
    }
    }




  • BuffyBot

    This is still dependent on the Random class. I have been using the code that was on the site in my original post. This is due to much statisical analysis showing the Random class doesn't do a very good job of actually giving random sequences. I am trying to apply the Mersenne Twister algorithm for random number generation if you are familiar and don't want to go to the linked site. I do believe what you are saying about it taking less than 1 millisecond could be the issue.

    Do you recommend a different random number generator that MT The program I am creating needs a shuffle algorithm and obviously needs good random number generation. Thanks.


  • Cezary Sliwa

    C:\Documents and Settings\Owner\My Documents\Visual Studio Projects\xxxx\R250_521.cs(12): Syntax error, bad array declarator. To declare a managed array the rank specifier precedes the variable's identifier

    points to the line:

    private int r250_buffer[250];

    the line below it has the same error. Red underscore on the '['.

    Also how hard will it be to convert this to produce a random number within a range


  • Ram Kinkar Pandey

    Why can't you get Random number with the Random class

    You can specify a seed for the Random algoritme.


    Random random = new Random();

    for( int i = 0; i < 100; i++ )
    {
    Console.WriteLine( random.Next() );
    }



    By default the Random class uses the TickCount as seed, but because the ticktime only change millisecond you can get the same numbers when seed isn't changed in you second generation.

    You can use a Random GUID for example to generate your own seed:


    public sealed class RandomUtility
    {
    private RandomUtility() {}
    public static Random SeedRandom()
    {
    byte[] guid = Guid.NewGuid().ToByteArray();
    int seed = guid[0] + (guid[1] << 8) +
    (guid[2] << 16) + (guid[3] << 24);
    return new Random(seed);
    }
    }




  • Jack Gamble

    This is a great forum and very helpful.  I have decided to use Random just so that I can move on.  If anyone reading this has some advice on how I could switch out Random with a different class that is working (I had nothing but problems with the other RNGs) please help out.  Here is what I ended up doing:  (thanks to everyone who posted and I changed the RandomUtility already posted because I didn't know how to use the interface)

    public class RandomUtility

    {

    public RandomUtility()

    {

    }

    public int SeedRandom()

    {

    byte[] guid = Guid.NewGuid().ToByteArray();

    int seed = guid[0] + (guid[1] << 8) +

    (guid[2] << 16) + (guid[3] << 24);

    byte[] randomBytes = new byte[4];

    // Generate 4 random bytes.

    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

    rng.GetBytes(randomBytes);

    // Convert 4 bytes into a 32-bit integer value.

    int seed2 = (randomBytes[0] & 0x7f) << 24 |

    randomBytes[1] << 16 |

    randomBytes[2] << 8 |

    randomBytes[3];

    seed = seed ^ seed2;

    return seed;

    }

    }

     

    I then just pass this seed into the .NET Random() class.  Thanks for the help!


  • Mac7

    The built-in .Net Random class does NOT have a long enough period for some uses; in particular, it is not good for randomizing large sequences (such as a large deck of cards).

    For such uses, a Mersenne Twister is much better. But note that for cryptographical applications, a Mersenne Twister is not secure enough and you have to use some other random number generator.

  • sqsAndres

    you can create your random object with a timer generated seed...

    Random rnd = new Random(DateTime.Now.Millisecond);

    HTH,


  • ronmac

    I'd like to use the MersenneTwister class, but part of the code above is unreadable because the forum replaces it with icons.

    Where can I find the original The site mentioned in the code is hard to navigate.

    Edit: never mind, I found it at http://www.centerspace.net/resources.php.

    Thanks,

      Guido

     

     

     


  • kdogg2188

    Apparently, a faulty translation from c++. The line should read:

    private int[] r250_buffer = new int[250];



  • Having troubles with Randomness