/* ***************************************************************************
* Copyright (C) 2007 Urban Hafner, Jason House *
* *
* This file is part of HouseBot. *
* *
* HouseBot is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 3 of the License, or *
* (at your option) any later version. *
* *
* HouseBot is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see . *
* *
*****************************************************************************/
/// Pseudo random number generators (Mersenne Twister)
module random;
import tango.math.Random : Random; // used for default seed
import tango.math.Math : ceil, max, sqrt;
import log : hberr;
/// Implementation of the Mersenne Twister PRNG
class MersenneTwister {
/// Initialize random number generator with seed
this(uint seed) { init_genrand(seed); }
/// Initializes random number generator with seed generated by rand()
/// from std.random.
this() { Random r = new Random(); this(r.next); }
/// Returns the next random integer
uint nextUInt() { return cast(uint)genrand_int32(); }
/// ditto
ulong nextULong() {
uint upperHalf = cast(uint)genrand_int32();
uint lowerHalf = cast(uint)genrand_int32();
ulong rv = upperHalf;
rv = (rv<<32) + (cast(ulong)lowerHalf);
return rv;
}
/// Returns the next random double between 0 and 1 inclusive
double nextDouble() { return genrand_real1(); }
unittest {
scope MersenneTwister mt = new MersenneTwister();
mt.nextUInt();
mt.nextDouble();
}
unittest {
bool runTest(int numBins, float threshold){
const int simsPerBin = 1000;
scope MersenneTwister mt = new MersenneTwister();
int[100000] result;
int[500] countByStandardDeviation;
for (int i=0; i<(simsPerBin*numBins); i++){
int val = mt.nextUInt() % numBins;
result[val] = result[val]+1;
}
float stddev = sqrt((1.0/numBins)*(1-(1.0/numBins))*simsPerBin*numBins);
for (int j=0; j 0){
debug(unitTest) hberr.formatln("{} std dev = {} bins", k*0.1, nSamples);
maxStdDev = 0.1*k;
}
}
if (maxStdDev > threshold)
hberr.formatln("Failed statistical test with {} standard deviations away instead of {}", maxStdDev, threshold);
return (maxStdDev<=threshold);
}
// Statistically speaking, this test should fail about 1% of the time
assert(runTest(10, 3.5), "Random sampling biased? (10 samples)");
assert(runTest(1000, 4.5), "Random sampling biased? (1,000 samples)");
//assert(runTest(100000, 5.5), "Random sampling biased? (100,000 samples)"); // Takes too long
}
// Everything below this point is copied from the original Mersenne
// Twister C code and changed to be valid D. The original copyright
// applies.
/*
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.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
/* Period parameters */
const uint N = 624;
const uint M = 397;
const ulong MATRIX_A = 0x9908b0dfUL; /* constant vector a */
const ulong UPPER_MASK = 0x80000000UL; /* most significant w-r bits */
const ulong LOWER_MASK = 0x7fffffffUL; /* least significant r bits */
ulong mt[N]; /* the array for the state vector */
int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
/* initializes mt[N] with a seed */
private void init_genrand(ulong s)
{
mt[0]= s & 0xffffffffUL;
for (mti=1; mti> 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] &= 0xffffffffUL;
/* for >32 bit machines */
}
}
/* generates a random number on [0,0xffffffff]-interval */
private ulong genrand_int32()
{
ulong y;
const static ulong mag01[2]=[0x0UL, MATRIX_A];
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
uint kk;
// if (mti == N+1) /* if init_genrand() has not been called, */
// init_genrand(5489UL); /* a default initial seed is used */
for (kk=0;kk> 1) ^ mag01[cast(uint)(y & 0x1UL)];
}
for (;kk> 1) ^ mag01[cast(uint)(y & 0x1UL)];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[cast(uint)(y & 0x1UL)];
mti = 0;
}
y = mt[mti++];
/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return y;
}
/* generates a random number on [0,0x7fffffff]-interval */
private long genrand_int31()
{
return cast(long)(genrand_int32()>>1);
}
/* generates a random number on [0,1]-real-interval */
private double genrand_real1()
{
return genrand_int32()*(1.0/4294967295.0);
/* divided by 2^32-1 */
}
/* generates a random number on [0,1)-real-interval */
private double genrand_real2()
{
return genrand_int32()*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on (0,1)-real-interval */
private double genrand_real3()
{
return ((cast(double)genrand_int32()) + 0.5)*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on [0,1) with 53-bit resolution*/
private double genrand_res53()
{
ulong 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 */
}