473,511 Members | 14,933 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

The Mersenne Twister - please help

Hi Everyone,
I have this code of Mersenne twister, which produces the random
numbers, one of the fastest codes as far as I know to produce random
numbers.
Anyways, it's writen in c# and I need to translate it to vb.net.
I tried some translators and I can't get it to work.
Could someone help me?

This is the code:
using System;

namespace CenterSpace.Free
{
/// <summary>
/// Class MersenneTwister generates random numbers from a uniform
distribution using
/// the Mersenne Twister algorithm.
/// </summary>
/// <remarks>Caution: MT is for MonteCarlo, and is NOT
SECURE for CRYPTOGRAPHY
/// as it is.</remarks>
public class MersenneTwister
{
#region Constants
-------------------------------------------------------

// Period parameters.
private const int N = 624;
private const int M = 397;
private const uint MATRIX_A = 0x9908b0dfU; // constant vector 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 vector
private uint[] mt = new uint[N];

// mti==N+1 means mt[N] is not initialized
private int mti = N+1;

#endregion Instance Variables

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

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

/// <summary>
/// Creates a random number generator initialized with the given
seed.
/// </summary>
/// <param name="seed">The seed.</param>
public MersenneTwister( int seed )
{
init_genrand( (uint)seed );
}

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

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

#endregion Constructors

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

/// <summary>
/// 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 <c>0x7fffffff</c>
(<c>2,147,483,647</c>).
/// </summary>
public static int MaxRandomInt
{
get
{
return 0x7fffffff;
}
}

#endregion Properties

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

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

/// <summary>
/// Returns a positive random integer less than the specified
maximum.
/// </summary>
/// <param name="maxValue">The maximum value. Must
be greater than zero.</param>
/// <returns>A positive random integer less than or equal to
<c>maxValue</c>.</returns>
public int Next( int maxValue )
{
return Next( 0, maxValue );
}

/// <summary>
/// Returns a random integer within the specified range.
/// </summary>
/// <param name="minValue">The lower
bound.</param>
/// <param name="maxValue">The upper
bound.</param>
/// <returns>A random integer greater than or equal to
<c>minValue</c>, and less than
/// or equal to <c>maxValue</c>.</returns>
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) );
}

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

/// <summary>
/// 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.
/// </summary>
/// <param name="includeOne">
/// If <c>true</c>, the random number returned will be

/// less than or equal to one; otherwise, the random number
returned will
/// be strictly less than one.
/// </param>
/// <returns>
/// If <c>includeOne</c> is <c>true</c>,
this method returns a
/// single-precision random number greater than or equal to zero,
and less
/// than or equal to one. If <c>includeOne</c> is
<c>false</c>, this method
/// returns a single-precision random number greater than or equal
to zero and
/// strictly less than one.
/// </returns>
public float NextFloat( bool includeOne )
{
if ( includeOne )
{
return (float) genrand_real1();
}
return (float) genrand_real2();
}

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

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

/// <summary>
/// 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.
/// </summary>
/// <param name="includeOne">
/// If <c>true</c>, the random number returned will be

/// less than or equal to one; otherwise, the random number
returned will
/// be strictly less than one.
/// </param>
/// <returns>
/// If <c>includeOne</c> is <c>true</c>,
this method returns a
/// single-precision random number greater than or equal to zero,
and less
/// than or equal to one. If <c>includeOne</c> is
<c>false</c>, this method
/// returns a single-precision random number greater than or equal
to zero and
/// strictly less than one.
/// </returns>
public double NextDouble( bool includeOne )
{
if ( includeOne )
{
return genrand_real1();
}
return genrand_real2();
}

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

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

/// <summary>
/// Reinitializes the random number generator using the time of
day in
/// milliseconds as the seed.
/// </summary>
public void Initialize()
{
init_genrand( (uint)DateTime.Now.Millisecond );
}
/// <summary>
/// Reinitializes the random number generator with the given
seed.
/// </summary>
/// <param name="seed">The seed.</param>
public void Initialize( int seed )
{
init_genrand( (uint)seed );
}

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

init_by_array( initArray, (uint)initArray.Length
);
}
#region Methods ported from C
-------------------------------------------

// initializes mt[N] with a seed
private void init_genrand( uint s)
{
mt[0]= s & 0xffffffffU;
for (mti=1; mti<N; 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--)
{
mt[i] =
(uint)((uint)(mt[i] ^
((mt[i-1] ^ (mt[i-1] >>
30)) * 1664525U)) + init_key[j] + j); /*
non linear */
mt[i] &= 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--)
{
mt[i] =
(uint)((uint)(mt[i] ^
((mt[i-1] ^ (mt[i-1] >>
30)) * 1566083941U))- i); /* non linear */
mt[i] &= 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<N-M;kk++)
{
y =
(mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^
mag01[y & 0x1U];
}
for (;kk<N-1;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
}
}


And this is how to use it:
[code:1:ffb97307f8]
using System;

namespace CenterSpace.Free
{
/// <summary>
/// Simple example using the MersenneTwister class.
/// </summary>
class MersenneTwisterExample
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
MersenneTwister randGen = new MersenneTwister();
Console.WriteLine( "100 uniform random integers in
[0,{0}]:", MersenneTwister.MaxRandomInt
);
int i;
for ( i = 0; i < 100; ++i )
{
Console.Write( "{0} ",
randGen.Next() );
if ( i%5 == 4 )
Console.WriteLine("");
}

Console.WriteLine( "100 uniform random doubles in
[0,1):" );
for ( i = 0; i < 100; ++i )
{
Console.Write( "{0} ",
randGen.NextDouble().ToString("F8") );
if ( i%5 == 4 )
Console.WriteLine("");
}
}
}
}

[/code:1:ffb97307f8]

----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 20 '05 #1
2 3281
Cor
Hi Martin,

I do not think that there visists someone this newsgroup who will convert so
much code just for fun.

But here are links for language comparissing.

Code C# and VB
http://www.harding.edu/USER/fmccown/...omparison.html

Language compare
http://msdn.microsoft.com/library/en...quivalents.asp

And here some converter links maybe you can convert it first.
C# -> VB .NET Converters:

http://www.kamalpatel.net/ConvertCSharp2VB.aspx

http://csharpconverter.claritycon.com/Default.aspx

http://www.ragingsmurf.com/vbcsharpconverter.aspx

http://www.aspalliance.com/aldotnet/...translate.aspx

http://www.gotdotnet.com/Community/U...7-979975d5957d
http://www.remotesoft.com/ look for "Octopus"
Mostly when you have detailed difficulties there is always someone here who
will help you.

I hope this helps a little bit?

Cor

I have this code of Mersenne twister, which produces the random
numbers, one of the fastest codes as far as I know to produce random
numbers.
Anyways, it's writen in c# and I need to translate it to vb.net.
I tried some translators and I can't get it to work.
Could someone help me?

Nov 20 '05 #2
Cor
Hi Martin,

I do not think that there visists someone this newsgroup who will convert so
much code just for fun.

But here are links for language comparissing.

Code C# and VB
http://www.harding.edu/USER/fmccown/...omparison.html

Language compare
http://msdn.microsoft.com/library/en...quivalents.asp

And here some converter links maybe you can convert it first.
C# -> VB .NET Converters:

http://www.kamalpatel.net/ConvertCSharp2VB.aspx

http://csharpconverter.claritycon.com/Default.aspx

http://www.ragingsmurf.com/vbcsharpconverter.aspx

http://www.aspalliance.com/aldotnet/...translate.aspx

http://www.gotdotnet.com/Community/U...7-979975d5957d
http://www.remotesoft.com/ look for "Octopus"
Mostly when you have detailed difficulties there is always someone here who
will help you.

I hope this helps a little bit?

Cor

I have this code of Mersenne twister, which produces the random
numbers, one of the fastest codes as far as I know to produce random
numbers.
Anyways, it's writen in c# and I need to translate it to vb.net.
I tried some translators and I can't get it to work.
Could someone help me?

Nov 20 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1200
by: jt | last post by:
I'm trying to learn how to use a seed for the random module that is larger than the integer produced by python's built-in hash(x) function. >From the documentation, it says: "If x is not None or...
31
4393
by: Scott Robert Ladd | last post by:
I've posted my revised C++ implementation of the Mersenne Twister at: http://www.coyotegulch.com/libcoyote/TwistedRoad/TwistedRoad.html This is "free-as-in-liberty" and "free-as-in-beer" code....
7
3570
by: x muzuo | last post by:
Hi guys, I have got a prob of javascript form validation which just doesnt work with my ASP code. Can any one help me out please. Here is the code: {////<<head> <title>IIBO Submit Page</title>...
23
3232
by: Jason | last post by:
Hi, I was wondering if any could point me to an example or give me ideas on how to dynamically create a form based on a database table? So, I would have a table designed to tell my application...
1
9586
by: David Van D | last post by:
Hi there, A few weeks until I begin my journey towards a degree in Computer Science at Canterbury University in New Zealand, Anyway the course tutors are going to be teaching us JAVA wth bluej...
11
2695
by: Simon | last post by:
I have a quick question on the Mersenne Twister (hereinafter MT) I'm using the standard C code downloaded from the MT website (http://tinyurl.com/6d8t3). It's being used for a game to generate...
24
2274
by: Nirjhar Oberoi | last post by:
TWISTER 2.1 ¿? Your have to take a decision in a program but the creator of the programming language forgot to supply the programmer with a IF-ELE Construct? Can you find a work arround? ...
40
3586
by: Spiros Bousbouras | last post by:
Do you have an example of an implementation where sizeof(short int) does not divide sizeof(int) or sizeof(int) does not divide sizeof(long int) or sizeof(long int) does not divide sizeof(long long...
0
1116
by: bearophileHUGS | last post by:
This may be interesting for Python developers of the random module, "SIMD-oriented Fast Mersenne Twister (SFMT): twice faster than Mersenne Twister": ...
0
7237
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7137
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7349
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
7074
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
4734
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3219
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3210
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1572
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
445
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.