📄 random.cpp
字号:
/*
streflop: STandalone REproducible FLOating-Point
Nicolas Brodu, 2006
Code released according to the GNU Lesser General Public License
Heavily relies on GNU Libm, itself depending on netlib fplibm, GNU MP, and IBM MP lib.
Uses SoftFloat too.
Please read the history and copyright information in the documentation provided with the source code
*/
// Include time(0) function to get a seed based on system time
#include <time.h>
#include <iostream>
using namespace std;
#include "streflop.h"
// Include endian-specific code
#undef __BYTE_ORDER
#undef __FLOAT_WORD_ORDER
#include "System.h"
namespace streflop {
//////////////////////////////////////////////////////////////////////
// Code stolen and adapted from mt19937ar.c
//////////////////////////////////////////////////////////////////////
/*
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.
Copyright (C) 2005, Mutsuo Saito,
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)
*/
#if STREFLOP_RANDOM_GEN_SIZE == 32
/* Period parameters */
#define N 624
#define M 397
#define MATRIX_A 0x9908b0dfUL /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
/* initializes mt[N] with a seed */
inline void init_genrand(SizedUnsignedInteger<32>::Type s, RandomState& state)
{
state.seed = s;
state.mt[0]= s; // & 0xffffffffUL; // NB060508: unnecessary with the use of sized types
for (state.mti=1; state.mti<N; state.mti++) {
state.mt[state.mti] =
(1812433253UL * (state.mt[state.mti-1] ^ (state.mt[state.mti-1] >> 30)) + state.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; // NB060508: unnecessary with the use of sized types
/* for >32 bit machines */
}
}
/* generates a random number on [0,0xffffffff]-interval */
inline SizedUnsignedInteger<32>::Type genrand_int(RandomState& state)
{
SizedUnsignedInteger<32>::Type y;
static SizedUnsignedInteger<32>::Type mag01[2]={0x0UL, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (state.mti >= N) { /* generate N words at one time */
int kk;
//if (state.mti == N+1) /* if init_genrand() has not been called, */
//init_genrand(5489UL, state); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++) {
y = (state.mt[kk]&UPPER_MASK)|(state.mt[kk+1]&LOWER_MASK);
state.mt[kk] = state.mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for (;kk<N-1;kk++) {
y = (state.mt[kk]&UPPER_MASK)|(state.mt[kk+1]&LOWER_MASK);
state.mt[kk] = state.mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (state.mt[N-1]&UPPER_MASK)|(state.mt[0]&LOWER_MASK);
state.mt[N-1] = state.mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
state.mti = 0;
}
y = state.mt[state.mti++];
/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return y;
}
#else
//////////////////////////////////////////////////////////////////////
// End of code adapted from mt19937ar.c
// Now adapt code from the 64-bit version in mt19937-64.c
//////////////////////////////////////////////////////////////////////
/*
A C-program for MT19937-64 (2004/9/29 version).
Coded by Takuji Nishimura and Makoto Matsumoto.
This is a 64-bit version of Mersenne Twister pseudorandom number
generator.
Before using, initialize the state by using init_genrand64(seed)
or init_by_array64(init_key, key_length).
Copyright (C) 2004, 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.
References:
T. Nishimura, ``Tables of 64-bit Mersenne Twisters''
ACM Transactions on Modeling and
Computer Simulation 10. (2000) 348--357.
M. Matsumoto and T. Nishimura,
``Mersenne Twister: a 623-dimensionally equidistributed
uniform pseudorandom number generator''
ACM Transactions on Modeling and
Computer Simulation 8. (Jan. 1998) 3--30.
Any feedback is very welcome.
http://www.math.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove spaces)
*/
#define NN 312
#define MM 156
#define MATRIX_A 0xB5026F5AA96619E9ULL
#define UM 0xFFFFFFFF80000000ULL /* Most significant 33 bits */
#define LM 0x7FFFFFFFULL /* Least significant 31 bits */
/* initializes mt[NN] with a seed */
inline void init_genrand(SizedUnsignedInteger<64>::Type seed, RandomState& state)
{
state.seed = seed;
state.mt[0] = seed;
for (state.mti=1; state.mti<NN; state.mti++)
state.mt[state.mti] = (SizedUnsignedInteger<64>::Type(6364136223846793005ULL) * (state.mt[state.mti-1] ^ (state.mt[state.mti-1] >> 62)) + state.mti);
}
/* generates a random number on [0, 2^64-1]-interval */
inline SizedUnsignedInteger<64>::Type genrand_int(RandomState& state)
{
int i;
SizedUnsignedInteger<64>::Type x;
static SizedUnsignedInteger<64>::Type mag01[2]={0ULL, MATRIX_A};
if (state.mti >= NN) { /* generate NN words at one time */
/* if init_genrand64() has not been called, */
/* a default initial seed is used */
//if (state.mti == NN+1)
//init_genrand64(5489ULL, state);
for (i=0;i<NN-MM;i++) {
x = (state.mt[i]&UM)|(state.mt[i+1]&LM);
state.mt[i] = state.mt[i+MM] ^ (x>>1) ^ mag01[(int)(x&1ULL)];
}
for (;i<NN-1;i++) {
x = (state.mt[i]&UM)|(state.mt[i+1]&LM);
state.mt[i] = state.mt[i+(MM-NN)] ^ (x>>1) ^ mag01[(int)(x&1ULL)];
}
x = (state.mt[NN-1]&UM)|(state.mt[0]&LM);
state.mt[NN-1] = state.mt[MM-1] ^ (x>>1) ^ mag01[(int)(x&1ULL)];
state.mti = 0;
}
x = state.mt[state.mti++];
x ^= (x >> 29) & 0x5555555555555555ULL;
x ^= (x << 17) & 0x71D67FFFEDA60000ULL;
x ^= (x << 37) & 0xFFF7EEE000000000ULL;
x ^= (x >> 43);
return x;
}
#endif
//////////////////////////////////////////////////////////////////////
// End of code adapted from mt19937-64.c
//////////////////////////////////////////////////////////////////////
// Bit getter utilities
template<int nbits> struct Accessor {
typedef typename SizedUnsignedInteger<nbits>::Type Type;
static inline Type getRandomInt(RandomState& state) {
return static_cast<Type>(genrand_int(state));
}
};
// Specialize for 32 bits generator case
#if STREFLOP_RANDOM_GEN_SIZE == 32
template<> struct Accessor<64> {
typedef SizedUnsignedInteger<64>::Type Type;
static inline Type getRandomInt(RandomState& state) {
return static_cast<Type>(genrand_int(state)) | (static_cast<Type>(genrand_int(state)) << 32);
}
};
#endif
// This code inspired from a trick found in Richard J. Wagner's Mersene class and the optimization
// by Magnus Jonsson, also found at http://aggregate.org.
// The trick consists in:
// - draw random numbers in as close as possible as the target
// - reject these which are out of range
// The goal is to avoid operator %
template<int bits_size> struct RandomIntRestrictor {
};
// for 8-bits
template<> struct RandomIntRestrictor<8> {
typedef SizedUnsignedInteger<8>::Type Type;
static inline Type getRestrictedRandomInt(Type n, RandomState& state)
{
// First propagate leading 1 to all other bits
Type mask = n;
mask |= mask >> 1;
mask |= mask >> 2;
mask |= mask >> 4;
// Draw only that number of bits, until a number is in the desired range [0,n]
// Worse case is number of loops proba decreasing in 1/2^nloops
Type ret;
do {
ret = Accessor<8>::getRandomInt(state) & mask;
} while( ret > n );
return ret;
}
};
// for 16-bits
template<> struct RandomIntRestrictor<16> {
typedef SizedUnsignedInteger<16>::Type Type;
static inline Type getRestrictedRandomInt(Type n, RandomState& state)
{
// First propagate leading 1 to all other bits
Type mask = n;
mask |= mask >> 1;
mask |= mask >> 2;
mask |= mask >> 4;
mask |= mask >> 8;
// Draw only that number of bits, until a number is in the desired range [0,n]
// Worse case is number of loops proba decreasing in 1/2^nloops
Type ret;
do {
ret = Accessor<16>::getRandomInt(state) & mask;
} while( ret > n );
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -