Added blitz

This commit is contained in:
Christian
2018-09-17 14:30:47 +02:00
parent f139994714
commit bd644ee60c
1271 changed files with 546295 additions and 98 deletions
+92
View File
@@ -0,0 +1,92 @@
// -*- C++ -*-
// $Id$
/*
* F distribution
*
* This code has been adapted from RANDLIB.C 1.3, by
* Barry W. Brown, James Lovato, Kathy Russell, and John Venier.
* Code was originally by Ahrens and Dieter (see above).
*
* Adapter's notes:
* BZ_NEEDS_WORK: how to handle seeding for the two gamma RNGs if
* independentState is used?
* BZ_NEEDS_WORK: code for handling possible overflow when xden
* is tiny seems a bit flaky.
*/
#ifndef BZ_RANDOM_F
#define BZ_RANDOM_F
#ifndef BZ_RANDOM_GAMMA
#include <random/gamma.h>
#endif
BZ_NAMESPACE(ranlib)
template<typename T = double, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class F {
public:
typedef T T_numtype;
F(T numeratorDF, T denominatorDF)
{
setDF(numeratorDF, denominatorDF);
mindenom = 0.085 * blitz::tiny(T());
}
F(T numeratorDF, T denominatorDF, unsigned int i) :
ngamma(i), dgamma(i)
{
setDF(numeratorDF, denominatorDF);
mindenom = 0.085 * blitz::tiny(T());
}
void setDF(T _dfn, T _dfd)
{
BZPRECONDITION(_dfn > 0.0);
BZPRECONDITION(_dfd > 0.0);
dfn = _dfn;
dfd = _dfd;
ngamma.setMean(dfn/2.0);
dgamma.setMean(dfd/2.0);
}
T random()
{
T xnum = 2.0 * ngamma.random() / dfn;
T xden = 2.0 * ngamma.random() / dfd;
// Rare event: Will an overflow probably occur?
if (xden <= mindenom)
{
// Yes, just return huge(T())
return blitz::huge(T());
}
return xnum / xden;
}
void seed(IRNG_int s, IRNG_int r)
{
// This is such a bad idea if independentState is used. Ugh.
// If sharedState is used, it is merely inefficient (the
// same RNG is seeded twice).
// yes it's unacceptable -- changed to using two seeds / Patrik
// in fact should probably be two uncorrelated IRNGs...
ngamma.seed(s);
dgamma.seed(r);
}
protected:
Gamma<T,IRNG,stateTag> ngamma, dgamma;
T dfn, dfd, mindenom;
};
BZ_NAMESPACE_END
#endif // BZ_RANDOM_F
+315
View File
@@ -0,0 +1,315 @@
// -*- C++ -*-
// $Id$
/*
* Generate Beta random deviate
*
* Returns a single random deviate from the beta distribution with
* parameters A and B. The density of the beta is
* x^(a-1) * (1-x)^(b-1) / B(a,b) for 0 < x < 1
*
* The mean is a/(a+b).
* The variance is ab/((a+b)^2(a+b+1))
* The rth moment is (a+r-1)^(r)/(a+b+r-1)^(r)
* where a^(r) means a * (a-1) * (a-2) * ... * (a-r+1)
*
* Method
* R. C. H. Cheng
* Generating Beta Variates with Nonintegral Shape Parameters
* Communications of the ACM, 21:317-322 (1978)
* (Algorithms BB and BC)
* http://www.acm.org/pubs/citations/journals/toms/1991-17-1/p98-l_ecuyer/
*
* This class has been adapted from RANDLIB.C 1.3, by
* Barry W. Brown, James Lovato, Kathy Russell, and John Venier.
*
* Adapter's note (TV): This code has gone from Pascal to Fortran to C.
* As a result it is a bit of a mess. Note also that the algorithms were
* originally designed for 32-bit float, and so some of the constants
* below have inadequate precision. This will not cause problems for
* casual use, but if you are generating millions of beta variates and
* rely on some convergence property, you may have want to worry
* about this.
*
* NEEDS_WORK: dig out the original paper and determine these constants
* to precision adequate for 128-bit float.
* NEEDS_WORK: turn this into structured code.
*/
#ifndef BZ_RANDOM_BETA
#define BZ_RANDOM_BETA
#ifndef BZ_RANDOM_UNIFORM
#include <random/uniform.h>
#endif
#ifndef BZ_NUMINQUIRE_H
#include <blitz/numinquire.h>
#endif
BZ_NAMESPACE(ranlib)
template<typename T = double, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class Beta : public UniformOpen<T,IRNG,stateTag>
{
public:
typedef T T_numtype;
Beta(T a, T b)
{
setParameters(a, b);
}
Beta(T a, T b, unsigned int i) : UniformOpen<T, IRNG, stateTag>(i)
{
setParameters(a, b);
}
T random();
void setParameters(T a, T b)
{
aa = a;
bb = b;
infnty = 0.3 * blitz::huge(T());
minlog = 0.085 * blitz::tiny(T());
expmax = log(infnty);
}
protected:
T ranf()
{
return UniformOpen<T,IRNG,stateTag>::random();
}
T aa, bb;
T infnty, minlog, expmax;
};
template<typename T, typename IRNG, typename stateTag>
T Beta<T,IRNG,stateTag>::random()
{
/* JJV changed expmax (log(1.0E38)==87.49823), and added minlog */
// TV: The original code had infnty = 1.0E38, minlog = 1.0E-37.
// I have changed these to 0.3 * huge and 8.5 * tiny. For IEEE
// float this works out to 1.020847E38 and 0.9991702E-37.
// I changed expmax from 87.49823 to log(infnty), which works out
// to 87.518866 for float.
static T olda = minlog;
static T oldb = minlog;
static T genbet,a,alpha,b,beta,delta,gamma,k1,k2,r,s,t,u1,u2,v,w,y,z;
static long qsame;
// This code determines if the aa and bb parameters are unchanged.
// If so, some code can be skipped.
qsame = (olda == aa) && (oldb == bb);
if (!qsame)
{
BZPRECHECK((aa > minlog) && (bb > minlog),
"Beta RNG: parameters must be >= " << minlog << endl
<< "Parameters are aa=" << aa << " and bb=" << bb << endl);
olda = aa;
oldb = bb;
}
if (!(min(aa,bb) > 1.0))
goto S100;
/*
Alborithm BB
Initialize
*/
if(qsame) goto S30;
a = min(aa,bb);
b = max(aa,bb);
alpha = a+b;
beta = sqrt((alpha-2.0)/(2.0*a*b-alpha));
gamma = a+1.0/beta;
S30:
S40:
u1 = ranf();
/*
Step 1
*/
u2 = ranf();
v = beta*log(u1/(1.0-u1));
/* JJV altered this */
if(v > expmax) goto S55;
/*
* JJV added checker to see if a*exp(v) will overflow
* JJV S50 _was_ w = a*exp(v); also note here a > 1.0
*/
w = exp(v);
if(w > infnty/a) goto S55;
w *= a;
goto S60;
S55:
w = infnty;
S60:
z = pow(u1,2.0)*u2;
r = gamma*v-1.3862944;
s = a+r-w;
/*
Step 2
*/
if(s+2.609438 >= 5.0*z) goto S70;
/*
Step 3
*/
t = log(z);
if(s > t) goto S70;
/*
* Step 4
*
* JJV added checker to see if log(alpha/(b+w)) will
* JJV overflow. If so, we count the log as -INF, and
* JJV consequently evaluate conditional as true, i.e.
* JJV the algorithm rejects the trial and starts over
* JJV May not need this here since alpha > 2.0
*/
if(alpha/(b+w) < minlog) goto S40;
if(r+alpha*log(alpha/(b+w)) < t) goto S40;
S70:
/*
Step 5
*/
if(!(aa == a)) goto S80;
genbet = w/(b+w);
goto S90;
S80:
genbet = b/(b+w);
S90:
goto S230;
S100:
/*
Algorithm BC
Initialize
*/
if(qsame) goto S110;
a = max(aa,bb);
b = min(aa,bb);
alpha = a+b;
beta = 1.0/b;
delta = 1.0+a-b;
k1 = delta*(1.38889E-2+4.16667E-2*b)/(a*beta-0.777778);
k2 = 0.25+(0.5+0.25/delta)*b;
S110:
S120:
u1 = ranf();
/*
Step 1
*/
u2 = ranf();
if(u1 >= 0.5) goto S130;
/*
Step 2
*/
y = u1*u2;
z = u1*y;
if(0.25*u2+z-y >= k1) goto S120;
goto S170;
S130:
/*
Step 3
*/
z = pow(u1,2.0)*u2;
if(!(z <= 0.25)) goto S160;
v = beta*log(u1/(1.0-u1));
/*
* JJV instead of checking v > expmax at top, I will check
* JJV if a < 1, then check the appropriate values
*/
if(a > 1.0) goto S135;
/* JJV a < 1 so it can help out if exp(v) would overflow */
if(v > expmax) goto S132;
w = a*exp(v);
goto S200;
S132:
w = v + log(a);
if(w > expmax) goto S140;
w = exp(w);
goto S200;
S135:
/* JJV in this case a > 1 */
if(v > expmax) goto S140;
w = exp(v);
if(w > infnty/a) goto S140;
w *= a;
goto S200;
S140:
w = infnty;
goto S200;
/*
* JJV old code
* if(!(v > expmax)) goto S140;
* w = infnty;
* goto S150;
*S140:
* w = a*exp(v);
*S150:
* goto S200;
*/
S160:
if(z >= k2) goto S120;
S170:
/*
Step 4
Step 5
*/
v = beta*log(u1/(1.0-u1));
/* JJV same kind of checking as above */
if(a > 1.0) goto S175;
/* JJV a < 1 so it can help out if exp(v) would overflow */
if(v > expmax) goto S172;
w = a*exp(v);
goto S190;
S172:
w = v + log(a);
if(w > expmax) goto S180;
w = exp(w);
goto S190;
S175:
/* JJV in this case a > 1.0 */
if(v > expmax) goto S180;
w = exp(v);
if(w > infnty/a) goto S180;
w *= a;
goto S190;
S180:
w = infnty;
/*
* JJV old code
* if(!(v > expmax)) goto S180;
* w = infnty;
* goto S190;
*S180:
* w = a*exp(v);
*/
S190:
/*
* JJV here we also check to see if log overlows; if so, we treat it
* JJV as -INF, which means condition is true, i.e. restart
*/
if(alpha/(b+w) < minlog) goto S120;
if(alpha*(log(alpha/(b+w))+v)-1.3862944 < log(z)) goto S120;
S200:
/*
Step 6
*/
if(!(a == aa)) goto S210;
genbet = w/(b+w);
goto S220;
S210:
genbet = b/(b+w);
S230:
S220:
return genbet;
}
BZ_NAMESPACE_END
#endif // BZ_RANDOM_BETA
+65
View File
@@ -0,0 +1,65 @@
// -*- C++ -*-
// $Id$
/*
* Chi^2 distribution
*
* This code has been adapted from RANDLIB.C 1.3, by
* Barry W. Brown, James Lovato, Kathy Russell, and John Venier.
* Code was originally by Ahrens and Dieter (see above).
*
* Adapter's notes:
*/
#ifndef BZ_RANDOM_CHISQUARE
#define BZ_RANDOM_CHISQUARE
#ifndef BZ_RANDOM_GAMMA
#include <random/gamma.h>
#endif
BZ_NAMESPACE(ranlib)
template<typename T = double, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class ChiSquare : public Gamma<T,IRNG,stateTag>
{
public:
typedef T T_numtype;
ChiSquare(T df)
: Gamma<T,IRNG,stateTag>(df/2.0) // isn't this redundant with setDF call?
{
setDF(df);
}
ChiSquare(T df, unsigned int i)
: Gamma<T,IRNG,stateTag>(df/2.0, i)
{
setDF(df);
}
void setDF(T _df)
{
BZPRECONDITION(_df > 0.0);
df = _df;
Gamma<T,IRNG,stateTag>::setMean(df/2.0);
}
T random()
{
return 2.0 * sgamma();
}
protected:
T sgamma()
{
return Gamma<T,IRNG,stateTag>::random();
}
T df;
};
BZ_NAMESPACE_END
#endif // BZ_RANDOM_CHISQUARE
+125
View File
@@ -0,0 +1,125 @@
// -*- C++ -*-
/***************************************************************************
* random/default.h Default IRNG wrapper class
*
* $Id$
*
* Copyright (C) 1997-2011 Todd Veldhuizen <tveldhui@acm.org>
*
* This file is a part of Blitz.
*
* Blitz is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* Blitz 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Blitz. If not, see <http://www.gnu.org/licenses/>.
*
* Suggestions: blitz-devel@lists.sourceforge.net
* Bugs: blitz-support@lists.sourceforge.net
*
* For more information, please see the Blitz++ Home Page:
* https://sourceforge.net/projects/blitz/
*
***************************************************************************/
#ifndef BZ_RANDOM_DEFAULT_H
#define BZ_RANDOM_DEFAULT_H
#include <random/mt.h>
BZ_NAMESPACE(ranlib)
// Some terminology:
// IRNG = Integer Random Number Generator. IRNGs generate random
// integers, which are used to create floating-point random
// numbers.
// RNG = Random Number Generator. RNGs use IRNGs to create floating-
// point random numbers following desired distributions.
typedef float defaultType;
// These are type tags. A RNG with sharedState shares an IRNG
// with other RNGs. An RNG with independentState
// contains its own IRNG. Generally, sharedState RNGs should be
// used.
struct sharedState { };
struct independentState { };
typedef sharedState defaultState;
typedef unsigned int IRNG_int;
// IRNGWrapper handles shared and independent state IRNGs.
// If a class inherits from IRNGWrapper<IRNG,sharedState>,
// it gets a static IRNG (i.e. the IRNG state is shared among
// all RNGs); if it inherits from IRNGWrapper<IRNG,independentState>,
// it gets an independent IRNG (the IRNG state is encapsulated
// in the RNG, and is not shared among RNGs).
template<typename IRNG, typename state>
class IRNGWrapper {
};
template<typename IRNG>
class IRNGWrapper<IRNG,sharedState> {
public:
void seed(IRNG_int x)
{ irng_.seed(x); }
void seed(std::vector<IRNG_int> x)
{ irng_.seed(x); }
typedef typename IRNG::T_state T_state;
T_state getState() const { return irng_.getState(); }
std::string getStateString() const { return irng_.getStateString(); }
void setState(const T_state& s) { irng_.setState(s); }
void setState(const std::string& s) { irng_.setState(s); }
protected:
static IRNG irng_;
};
template<typename IRNG>
IRNG IRNGWrapper<IRNG,sharedState>::irng_;
template<typename IRNG>
class IRNGWrapper<IRNG,independentState> {
public:
IRNGWrapper() {};
IRNGWrapper(unsigned int i) : irng_(MersenneTwisterCreator::create(i)) {};
void seed(IRNG_int x)
{ irng_.seed(x); }
void seed(std::vector<IRNG_int> x)
{ irng_.seed(x); }
typedef typename IRNG::T_state T_state;
T_state getState() const { return irng_.getState(); }
std::string getStateString() const { return irng_.getStateString(); }
void setState(const T_state& s) { irng_.setState(s); }
void setState(const std::string& s) { irng_.setState(s); }
protected:
IRNG irng_;
};
// defaultIRNG is a type alias for the default Integer Random
// Number Generator (IRNG).
typedef MersenneTwister defaultIRNG;
BZ_NAMESPACE_END
#endif // BZ_RANDOM_DEFAULT_H
+70
View File
@@ -0,0 +1,70 @@
// -*- C++ -*-
/***************************************************************************
* random/discrete-uniform.h Discrete uniform IRNG wrapper class
*
* $Id$
*
* Copyright (C) 1997-2011 Todd Veldhuizen <tveldhui@acm.org>
*
* This file is a part of Blitz.
*
* Blitz is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* Blitz 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Blitz. If not, see <http://www.gnu.org/licenses/>.
*
* Suggestions: blitz-devel@lists.sourceforge.net
* Bugs: blitz-support@lists.sourceforge.net
*
* For more information, please see the Blitz++ Home Page:
* https://sourceforge.net/projects/blitz/
*
***************************************************************************/
#ifndef BZ_RANDOM_DISCRETE_UNIFORM_H
#define BZ_RANDOM_DISCRETE_UNIFORM_H
#include <random/default.h>
BZ_NAMESPACE(ranlib)
template<typename T = unsigned int, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class DiscreteUniform : public IRNGWrapper<IRNG,stateTag>
{
public:
typedef T T_numtype;
DiscreteUniform(T n)
{
BZPRECONDITION(n < 4294967295U);
n_ = n;
}
DiscreteUniform(T n, unsigned int i) :
IRNGWrapper<IRNG,stateTag>::IRNGWrapper(i)
{
BZPRECONDITION(n < 4294967295U);
n_ = n;
}
T random()
{
return this->irng_.random() % n_;
}
private:
T n_;
};
BZ_NAMESPACE_END
#endif // BZ_RANDOM_DISCRETE_UNIFORM_H
+78
View File
@@ -0,0 +1,78 @@
// -*- C++ -*-
// $Id$
/*
* This generator uses the straightforward transformation
* x = - log(y) * m
*
* to turn a uniform (0,1) y into an exponentially distributed
* variable x. x has density function
*
* f(x) = (1/m) exp(-(1/m)x) (x > 0)
*
* and mean m.
*
* NEEDS_WORK: Adapt the method of Ahrens and Dieter. This will
* require extending the precision of the constants.
*
* Ahrens, J.H. and Dieter, U. Computer Methods for Sampling From the
* Exponential and Normal Distributions. Comm. ACM, 15,10 (Oct. 1972), p. 873.
*/
#ifndef BZ_RANDOM_EXPONENTIAL
#define BZ_RANDOM_EXPONENTIAL
#ifndef BZ_RANDOM_UNIFORM
#include <random/uniform.h>
#endif
BZ_NAMESPACE(ranlib)
template<typename T = double, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class ExponentialUnit : public UniformOpen<T,IRNG,stateTag>
{
public:
typedef T T_numtype;
ExponentialUnit() {}
explicit ExponentialUnit(unsigned int i) :
UniformOpen<T,IRNG,stateTag>(i) {};
T random()
{
return - log(UniformOpen<T,IRNG,stateTag>::random());
}
};
template<typename T = double, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class Exponential : public ExponentialUnit<T,IRNG,stateTag> {
public:
typedef T T_numtype;
Exponential(T mean)
{
mean_ = mean;
}
Exponential(T mean, unsigned int i) :
UniformOpen<T,IRNG,stateTag>(i)
{
mean_ = mean;
};
T random()
{
return mean_ * ExponentialUnit<T,IRNG,stateTag>::random();
}
private:
T mean_;
};
BZ_NAMESPACE_END
#endif // BZ_RANDOM_EXPONENTIAL
+316
View File
@@ -0,0 +1,316 @@
// -*- C++ -*-
// $Id$
/*
* Gamma distribution
*
* Source: Ahrens, J.H. and Dieter, U., Generating Gamma variates
* by a modified rejection technique. Comm. ACM, 25,1 (Jan. 1982)
* pp. 47-54.
*
* This code has been adapted from RANDLIB.C 1.3, by
* Barry W. Brown, James Lovato, Kathy Russell, and John Venier.
* Code was originally by Ahrens and Dieter (see above).
*
* Adapter's notes:
* NEEDS_WORK: more precision for literals.
* NEEDS_WORK: ideally the normal_ member should be driven from
* the same IRNG as the Gamma object, in the event that independentState
* is used. Not clear how this could be accomplished.
*/
#ifndef BZ_RANDOM_GAMMA
#define BZ_RANDOM_GAMMA
#ifndef BZ_RANDOM_UNIFORM
#include <random/uniform.h>
#endif
#ifndef BZ_RANDOM_NORMAL
#include <random/normal.h>
#endif
#ifndef BZ_RANDOM_EXPONENTIAL
#include <random/exponential.h>
#endif
#ifndef BZ_NUMINQUIRE_H
#include <blitz/numinquire.h>
#endif
BZ_NAMESPACE(ranlib)
template<typename T = double, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class Gamma : public UniformOpen<T,IRNG,stateTag>
{
public:
typedef T T_numtype;
Gamma()
{
setMean(1.0);
}
explicit Gamma(unsigned int i) :
UniformOpen<T,IRNG,stateTag>(i)
{
setMean(1.0);
};
Gamma(T mean)
{
setMean(mean);
}
Gamma(T mean, unsigned int i) :
UniformOpen<T,IRNG,stateTag>(i)
{
setMean(mean);
};
T random();
void setMean(T mean)
{
BZPRECONDITION(mean >= 1.0);
a = mean;
}
protected:
T ranf()
{
return UniformOpen<T,IRNG,stateTag>::random();
}
T snorm()
{
return normal_.random();
}
T sexpo()
{
return exponential_.random();
}
T fsign(T num, T sign)
{
/* Transfers sign of argument sign to argument num */
if ((sign>0.0L && num<0.0L)||(sign<0.0L && num>0.0L))
return -num;
else
return num;
}
NormalUnit<T,IRNG,sharedState> normal_;
ExponentialUnit<T,IRNG,sharedState> exponential_;
T a;
};
template<typename T, typename IRNG, typename stateTag>
T Gamma<T,IRNG,stateTag>::random()
{
/*
INPUT: A =PARAMETER (MEAN) OF THE STANDARD GAMMA DISTRIBUTION
OUTPUT: SGAMMA = SAMPLE FROM THE GAMMA-(A)-DISTRIBUTION
COEFFICIENTS Q(K) - FOR Q0 = SUM(Q(K)*A**(-K))
COEFFICIENTS A(K) - FOR Q = Q0+(T*T/2)*SUM(A(K)*V**K)
COEFFICIENTS E(K) - FOR EXP(Q)-1 = SUM(E(K)*Q**K)
PREVIOUS A PRE-SET TO ZERO - AA IS A', AAA IS A"
SQRT32 IS THE SQUAREROOT OF 32 = 5.656854249492380
*/
static T q1 = 4.166669E-2;
static T q2 = 2.083148E-2;
static T q3 = 8.01191E-3;
static T q4 = 1.44121E-3;
static T q5 = -7.388E-5;
static T q6 = 2.4511E-4;
static T q7 = 2.424E-4;
static T a1 = 0.3333333;
static T a2 = -0.250003;
static T a3 = 0.2000062;
static T a4 = -0.1662921;
static T a5 = 0.1423657;
static T a6 = -0.1367177;
static T a7 = 0.1233795;
static T e1 = 1.0;
static T e2 = 0.4999897;
static T e3 = 0.166829;
static T e4 = 4.07753E-2;
static T e5 = 1.0293E-2;
static T aa = 0.0;
static T aaa = 0.0;
static T sqrt32 = 5.656854249492380195206754896838792314280;
/* JJV added b0 to fix rare and subtle bug */
static T sgamma,s2,s,d,t,x,u,r,q0,b,b0,si,c,v,q,e,w,p;
if(a == aa) goto S10;
if(a < 1.0) goto S120;
/*
STEP 1: RECALCULATIONS OF S2,S,D IF A HAS CHANGED
*/
aa = a;
s2 = a-0.5;
s = sqrt(s2);
d = sqrt32-12.0*s;
S10:
/*
STEP 2: T=STANDARD NORMAL DEVIATE,
X=(S,1/2)-NORMAL DEVIATE.
IMMEDIATE ACCEPTANCE (I)
*/
t = snorm();
x = s+0.5*t;
sgamma = x*x;
if(t >= 0.0) return sgamma;
/*
STEP 3: U= 0,1 -UNIFORM SAMPLE. SQUEEZE ACCEPTANCE (S)
*/
u = ranf();
if(d*u <= t*t*t) return sgamma;
/*
STEP 4: RECALCULATIONS OF Q0,B,SI,C IF NECESSARY
*/
if(a == aaa) goto S40;
aaa = a;
r = 1.0/ a;
q0 = ((((((q7*r+q6)*r+q5)*r+q4)*r+q3)*r+q2)*r+q1)*r;
/*
APPROXIMATION DEPENDING ON SIZE OF PARAMETER A
THE CONSTANTS IN THE EXPRESSIONS FOR B, SI AND
C WERE ESTABLISHED BY NUMERICAL EXPERIMENTS
*/
if(a <= 3.686) goto S30;
if(a <= 13.022) goto S20;
/*
CASE 3: A .GT. 13.022
*/
b = 1.77;
si = 0.75;
c = 0.1515/s;
goto S40;
S20:
/*
CASE 2: 3.686 .LT. A .LE. 13.022
*/
b = 1.654+7.6E-3*s2;
si = 1.68/s+0.275;
c = 6.2E-2/s+2.4E-2;
goto S40;
S30:
/*
CASE 1: A .LE. 3.686
*/
b = 0.463+s+0.178*s2;
si = 1.235;
c = 0.195/s-7.9E-2+1.6E-1*s;
S40:
/*
STEP 5: NO QUOTIENT TEST IF X NOT POSITIVE
*/
if(x <= 0.0) goto S70;
/*
STEP 6: CALCULATION OF V AND QUOTIENT Q
*/
v = t/(s+s);
if(fabs(v) <= 0.25) goto S50;
q = q0-s*t+0.25*t*t+(s2+s2)*log(1.0+v);
goto S60;
S50:
q = q0+0.5*t*t*((((((a7*v+a6)*v+a5)*v+a4)*v+a3)*v+a2)*v+a1)*v;
S60:
/*
STEP 7: QUOTIENT ACCEPTANCE (Q)
*/
if(log(1.0-u) <= q) return sgamma;
S70:
/*
STEP 8: E=STANDARD EXPONENTIAL DEVIATE
U= 0,1 -UNIFORM DEVIATE
T=(B,SI)-DOUBLE EXPONENTIAL (LAPLACE) SAMPLE
*/
e = sexpo();
u = ranf();
u += (u-1.0);
t = b+fsign(si*e,u);
/*
STEP 9: REJECTION IF T .LT. TAU(1) = -.71874483771719
*/
if(t < -0.7187449) goto S70;
/*
STEP 10: CALCULATION OF V AND QUOTIENT Q
*/
v = t/(s+s);
if(fabs(v) <= 0.25) goto S80;
q = q0-s*t+0.25*t*t+(s2+s2)*log(1.0+v);
goto S90;
S80:
q = q0+0.5*t*t*((((((a7*v+a6)*v+a5)*v+a4)*v+a3)*v+a2)*v+a1)*v;
S90:
/*
STEP 11: HAT ACCEPTANCE (H) (IF Q NOT POSITIVE GO TO STEP 8)
*/
if(q <= 0.0) goto S70;
if(q <= 0.5) goto S100;
/*
* JJV modified the code through line 115 to handle large Q case
*/
if(q < 15.0) goto S95;
/*
* JJV Here Q is large enough that Q = log(exp(Q) - 1.0) (for real Q)
* JJV so reformulate test at 110 in terms of one EXP, if not too big
* JJV 87.49823 is close to the largest real which can be
* JJV exponentiated (87.49823 = log(1.0E38))
*/
if((q+e-0.5*t*t) > 87.49823) goto S115;
if(c*fabs(u) > exp(q+e-0.5*t*t)) goto S70;
goto S115;
S95:
w = exp(q)-1.0;
goto S110;
S100:
w = ((((e5*q+e4)*q+e3)*q+e2)*q+e1)*q;
S110:
/*
IF T IS REJECTED, SAMPLE AGAIN AT STEP 8
*/
if(c*fabs(u) > w*exp(e-0.5*t*t)) goto S70;
S115:
x = s+0.5*t;
sgamma = x*x;
return sgamma;
S120:
/*
ALTERNATE METHOD FOR PARAMETERS A BELOW 1 (.3678794=EXP(-1.))
JJV changed B to B0 (which was added to declarations for this)
JJV in 120 to END to fix rare and subtle bug.
JJV Line: 'aa = 0.0' was removed (unnecessary, wasteful).
JJV Reasons: the state of AA only serves to tell the A >= 1.0
JJV case if certain A-dependent constants need to be recalculated.
JJV The A < 1.0 case (here) no longer changes any of these, and
JJV the recalculation of B (which used to change with an
JJV A < 1.0 call) is governed by the state of AAA anyway.
aa = 0.0;
*/
b0 = 1.0+0.3678794*a;
S130:
p = b0*ranf();
if(p >= 1.0) goto S140;
sgamma = exp(log(p)/ a);
if(sexpo() < sgamma) goto S130;
return sgamma;
S140:
sgamma = -log((b0-p)/ a);
if(sexpo() < (1.0-a)*log(sgamma)) goto S130;
return sgamma;
}
BZ_NAMESPACE_END
#endif // BZ_RANDOM_GAMMA
+344
View File
@@ -0,0 +1,344 @@
// -*- C++ -*-
/*
* $Id$
*
* A C-program for MT19937: Integer version (1998/4/6)
* genrand() generates one pseudorandom unsigned integer (32bit)
* which is uniformly distributed among 0 to 2^32-1 for each
* call. sgenrand(seed) set initial values to the working area
* of 624 words. Before genrand(), sgenrand(seed) must be
* called once. (seed is any 32-bit integer except for 0).
* Coded by Takuji Nishimura, considering the suggestions by
* Topher Cooper and Marc Rieffel in July-Aug. 1997.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later
* version.
* This library 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 Library General Public License for more details.
* You should have received a copy of the GNU Library General
* Public License along with this library; if not, write to the
* Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*
* Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura.
* When you use this, send an email to: matumoto@math.keio.ac.jp
* with an appropriate reference to your work.
*
* REFERENCE
* M. Matsumoto and T. Nishimura,
* "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
* Pseudo-Random Number Generator",
* ACM Transactions on Modeling and Computer Simulation,
* Vol. 8, No. 1, January 1998, pp 3--30.
*
* See
* http://www.math.keio.ac.jp/~matumoto/emt.html
* and
* http://www.acm.org/pubs/citations/journals/tomacs/1998-8-1/p3-matsumoto/
*
*/
#ifndef BZ_RAND_MT
#define BZ_RAND_MT
#include <blitz/blitz.h>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <iterator>
#ifndef UINT_MAX
#include <limits.h>
#endif
#ifdef BZ_HAVE_BOOST_SERIALIZATION
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#endif
BZ_NAMESPACE(ranlib)
#if UINT_MAX < 4294967295U
typedef unsigned long twist_int; // must be at least 32 bits
#else
typedef unsigned int twist_int;
#endif
class MersenneTwister
{
public:
private:
#if defined(BZ_HAVE_NAMESPACES) && defined(BZ_HAVE_STD)
typedef std::vector<twist_int> State;
#else
typedef vector<twist_int> State;
#endif
typedef State::size_type SizeType;
typedef State::iterator Iter;
// Implements Step 2 and half of Step 3 in the MN98 description
struct BitMixer {
BitMixer() : s0(0), K(0x9908b0df) {};
BitMixer(twist_int k) : s0(0), K(k) {};
// Return 0 if lsb of s1=0, a if lsb of s1=1.
inline twist_int low_mask (twist_int s1) const {
// This does not actually result in a branch because it's
// equivalent to ( -(s1 & 1u) ) & K
return (s1&1u) ? K : 0u;
}
// Return y>>1 in MN98 (step 2 + part of 3).
// y = (x[i] AND u) OR (x[i+1 mod n] AND ll), where s0=x[i] and
// s1=x[i+1 mod n]
inline twist_int high_mask (twist_int s1) const {
return ( (s0&0x80000000) | (s1&0x7fffffff) ) >>1;
}
// Calculate (half of) step 3 in MN98.
inline twist_int operator() (twist_int s1) {
// (y>>1) XOR (0 if lsb of s1=0, a if lsb of s1=1)
// x[i+m] is XORed in reload
// (Note that it is OK to call low_mask with s1 (x[i+1]) and not
// with y, like MN98 does, because s1&1 == y&1 by construction.
twist_int r = high_mask(s1) ^ low_mask(s1);
s0 = s1;
return r;
}
twist_int s0; // this is "x[i]" in the MN98 description
const twist_int K; // MN98 "a" vector
};
enum { N = 624,
PF = 397, // MN98 "m"
reference_seed = 4357 };
void initialize()
{
S.resize(N);
I = S.end();
}
public:
MersenneTwister() : b_(0x9D2C5680), c_(0xEFC60000)
{
initialize();
seed();
// There is a problem: static initialization + templates do not
// mix very well in C++. If you have a static member
// of a class template, there is no guarantee on its order iin
// static initialization. This MersenneTwister class is used
// elsewhere as a static member of a template class, and it is
// possible (in fact, I've done so) to create a static initializer
// that will invoke the seed() method of this object before its
// ctor has been called (result: crash).
// ANSI C++ is stranger than fiction.
// Currently the documentation forbids using RNGs from
// static initializers. There doesn't seem to be a good
// fix.
}
MersenneTwister(twist_int aa, twist_int bb, twist_int cc) :
twist_(aa), b_(bb), c_(cc)
{
initialize();
seed();
}
MersenneTwister(twist_int initial_seed) : b_(0x9D2C5680), c_(0xEFC60000)
{
initialize();
seed(initial_seed);
}
MersenneTwister(twist_int aa, twist_int bb, twist_int cc,
twist_int initial_seed) : twist_(aa), b_(bb), c_(cc)
{
initialize();
seed(initial_seed);
}
// Seed. Uses updated seed algorithm from mt19937ar. The old
// algorithm would yield sequences that were close from seeds that
// were close.
void seed (twist_int seed = reference_seed)
{
// seed cannot equal 0
if (seed == 0)
seed = reference_seed;
S[0] = seed & 0xFFFFFFFF;
for (SizeType mti=1; mti<S.size(); ++mti) {
S[mti] = (1812433253U * (S[mti-1] ^ (S[mti-1] >> 30)) + mti);
S[mti] &= 0xffffffffU;
}
reload();
}
// Seed by array, swiped directly from mt19937ar. Gives a larger
// initial seed space.
void seed (State seed_vector)
{
SizeType i, j, k;
seed(19650218U);
i=1; j=0;
const SizeType N=S.size();
const SizeType n=seed_vector.size();
k = (N>n ? N : n);
for (; k; k--) {
S[i] = (S[i] ^ ((S[i-1] ^ (S[i-1] >> 30)) * 1664525U))
+ seed_vector[j] + j; /* non linear */
S[i] &= 0xffffffffU; /* for WORDSIZE > 32 machines */
i++; j++;
if (i>=N) { S[0] = S[N-1]; i=1; }
if (j>=n) j=0;
}
for (k=N-1; k; k--) {
S[i] = (S[i] ^ ((S[i-1] ^ (S[i-1] >> 30)) * 1566083941UL))
- i; /* non linear */
S[i] &= 0xffffffffU; /* for WORDSIZE > 32 machines */
i++;
if (i>=N) { S[0] = S[N-1]; i=1; }
}
S[0] = 0x80000000U; /* MSB is 1; assuring non-zero initial array */
reload();
}
// generate a full new x array
void reload (void)
{
// This check is required because it is possible to call random()
// before the constructor. See the note above about static
// initialization.
Iter p0 = S.begin();
Iter pM = p0 + PF;
twist_ (S[0]); // set x[i]=x[0] in the twister (prime the pump)
for (Iter pf_end = S.begin()+(N-PF); p0 != pf_end; ++p0, ++pM)
// mt[kk] = mt[kk+m] XOR ((y>>1)XOR(mag01), as calc by BitMixer)
*p0 = *pM ^ twist_ (p0[1]);
// This is the "modulo part" where kk+m rolls over
pM = S.begin();
for (Iter s_end = S.begin()+(N-1); p0 != s_end; ++p0, ++pM)
*p0 = *pM ^ twist_ (p0[1]);
// and final element where kk+1 rolls over
*p0 = *pM ^ twist_ (S[0]);
I = S.begin();
}
inline twist_int random (void)
{
if (I >= S.end()) reload();
// get next word from array
twist_int y = *I++;
// Step 4+5 in MN98, multiply by tempering matrix
y ^= (y >> 11);
y ^= (y << 7) & b_;
y ^= (y << 15) & c_;
y ^= (y >> 18);
return y;
}
// functions for getting/setting state
class mt_state {
friend class MersenneTwister;
private:
State S;
State::difference_type I;
public:
mt_state() { }
mt_state(State s, State::difference_type i) : S(s), I(i) { }
mt_state(const std::string& s) {
std::istringstream is(s);
is >> I;
S = State(std::istream_iterator<twist_int>(is),
std::istream_iterator<twist_int>());
assert(!S.empty());
}
operator bool() const { return !S.empty(); }
std::string str() const {
if (S.empty())
return std::string();
std::ostringstream os;
os << I << " ";
std::copy(S.begin(), S.end(),
std::ostream_iterator<twist_int>(os," "));
return os.str();
}
#ifdef BZ_HAVE_BOOST_SERIALIZATION
friend class boost::serialization::access;
/** Serialization operator. Relies on the ability to serialize
std::vector. */
template<class T_arch>
void serialize(T_arch& ar, const unsigned int version) {
ar & S & I;
};
#endif
};
typedef mt_state T_state;
T_state getState() const { return T_state(S, I-S.begin()); }
std::string getStateString() const {
T_state tmp(S, I-S.begin());
return tmp.str();
}
void setState(const T_state& s) {
if (!s) {
std::cerr << "Error: state is empty" << std::endl;
return;
}
S = s.S;
I = S.begin() + s.I;
}
void setState(const std::string& s) {
T_state tmp(s);
setState(tmp);
}
private:
BitMixer twist_;
const twist_int b_,c_;
State S;
Iter I;
};
/** This class creates MersenneTwisters with different parameters
indexed by and ID number. */
class MersenneTwisterCreator
{
public:
static MersenneTwister create(unsigned int i) {
// We only have n different parameter sets
i = i % n;
return MersenneTwister(a_[i], b_[i], c_[i]);
};
private:
static const unsigned int n=48;
static const twist_int a_[n];
static const twist_int b_[n];
static const twist_int c_[n];
};
BZ_NAMESPACE_END
#endif // BZ_RAND_MT
+48
View File
@@ -0,0 +1,48 @@
/*
* $Id$
*
* Static parameter combinations for MT19937.
*/
#include <random/mt.h>
BZ_NAMESPACE(ranlib)
const twist_int MersenneTwisterCreator::a_[] = {
0xcc420000, 0xabbe0001, 0xdabf0002, 0xbe010003, 0xd6db0004,
0xc36d0005, 0x84ce0006, 0xe6700007, 0xdc1e0008, 0xe1710009,
0xa2f4000a, 0xf22c000b, 0x936e000c, 0xf75d000d, 0xd547000e,
0xd8d7000f, 0xe5e40010, 0xf7cf0011, 0xec180012, 0xa4430013,
0xf81d0014, 0x82f50015, 0xf6100016, 0xcc360017, 0xae950018,
0xf3cb0019, 0x843e001a, 0x95570040, 0xcbfc0041, 0x976c0042,
0xddf50043, 0xfda50044, 0xea2a0045, 0xd6fa0046, 0x948d0060,
0xc42b0061, 0x8d580062, 0xa96c0063, 0xc1be0064, 0xc5030065,
0x8c6f0066, 0xc9490080, 0xab950081, 0xd6ef0082, 0xecb00083,
0xda4a0084, 0xbd190085, 0x8aaf0086 };
const twist_int MersenneTwisterCreator::b_[] = {
0xf3156f80, 0x5af53e80, 0x8cdd7780, 0xbb56ee80, 0x26eef680,
0xdd4eec80, 0x2656f480, 0xb914ee80, 0x8d5d7780, 0x2e753a80,
0xcd757780, 0x33b6bb80, 0xeaf4b680, 0x59ed3b80, 0xd674ea80,
0x66757b80, 0x24d53a80, 0xdccd7780, 0x66f77780, 0x66d57780,
0xb51f7780, 0x59a53a80, 0xec75bb80, 0x6e557b80, 0x8cad7780,
0x8cd56f80, 0x99a6ba80, 0xbad5bb80, 0xa7f77680, 0xbbefbe80,
0xdccd7780, 0x6296ee80, 0x9dd4b580, 0x66f77680, 0xeef57680,
0xeb35b480, 0xa6df7680, 0xf35d6d80, 0xf7557780, 0xbbb5bb80,
0xf7b57680, 0xbad5bb80, 0xedf5bb80, 0xdcad7780, 0xdcd57780,
0x73557b00, 0x4cf53a80, 0x5a6d3a80 };
const twist_int MersenneTwisterCreator::c_[] = {
0xdd558000, 0xf6d78000, 0xee778000, 0xddd58000, 0xeec58000,
0xefd38000, 0xefd58000, 0xddd58000, 0xee778000, 0xf7d48000,
0xee558000, 0xf7558000, 0x77d28000, 0xf7658000, 0xefd58000,
0xf7558000, 0xf7d48000, 0xed758000, 0xee538000, 0xef778000,
0xd7758000, 0xf7f58000, 0xbb578000, 0xf7708000, 0xee778000,
0xee5f8000, 0xf7f58000, 0xf7558000, 0xd6d18000, 0xf6cb8000,
0xee778000, 0xdbd38000, 0xf7d58000, 0xeef38000, 0xddd48000,
0x77d78000, 0xd6e38000, 0x6fd58000, 0xee558000, 0x77518000,
0xddd58000, 0xf7558000, 0x7b558000, 0xee758000, 0xee778000,
0xe6d78000, 0xf7d48000, 0xf3f48000 };
BZ_NAMESPACE_END
+120
View File
@@ -0,0 +1,120 @@
// -*- C++ -*-
// $Id$
/*
* This is a modification of the Kinderman + Monahan algorithm for
* generating normal random numbers, due to Leva:
*
* J.L. Leva, Algorithm 712. A normal random number generator, ACM Trans.
* Math. Softw. 18 (1992) 454--455.
*
* http://www.acm.org/pubs/citations/journals/toms/1992-18-4/p449-leva/
*
* Note: Some of the constants used below look like they have dubious
* precision. These constants are used for an approximate bounding
* region test (see the paper). If the approximate test fails,
* then an exact region test is performed.
*
* Only 0.012 logarithm evaluations are required per random number
* generated, making this method comparatively fast.
*
* Adapted to C++ by T. Veldhuizen.
*/
#ifndef BZ_RANDOM_NORMAL
#define BZ_RANDOM_NORMAL
#ifndef BZ_RANDOM_UNIFORM
#include <random/uniform.h>
#endif
BZ_NAMESPACE(ranlib)
template<typename T = double, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class NormalUnit : public UniformOpen<T,IRNG,stateTag>
{
public:
typedef T T_numtype;
NormalUnit() {}
explicit NormalUnit(unsigned int i) :
UniformOpen<T,IRNG,stateTag>(i) {};
T random()
{
const T s = 0.449871, t = -0.386595, a = 0.19600, b = 0.25472;
const T r1 = 0.27597, r2 = 0.27846;
T u, v;
for (;;) {
// Generate P = (u,v) uniform in rectangle enclosing
// acceptance region:
// 0 < u < 1
// - sqrt(2/e) < v < sqrt(2/e)
// The constant below is 2*sqrt(2/e).
u = this->getUniform();
v = 1.715527769921413592960379282557544956242L
* (this->getUniform() - 0.5);
// Evaluate the quadratic form
T x = u - s;
T y = fabs(v) - t;
T q = x*x + y*(a*y - b*x);
// Accept P if inside inner ellipse
if (q < r1)
break;
// Reject P if outside outer ellipse
if (q > r2)
continue;
// Between ellipses: perform exact test
if (v*v <= -4.0 * log(u)*u*u)
break;
}
return v/u;
}
};
template<typename T = double, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class Normal : public NormalUnit<T,IRNG,stateTag> {
public:
typedef T T_numtype;
Normal(T mean, T standardDeviation)
{
mean_ = mean;
standardDeviation_ = standardDeviation;
}
Normal(T mean, T standardDeviation, unsigned int i) :
NormalUnit<T,IRNG,stateTag>(i)
{
mean_ = mean;
standardDeviation_ = standardDeviation;
};
T random()
{
return mean_ + standardDeviation_
* NormalUnit<T,IRNG,stateTag>::random();
}
private:
T mean_;
T standardDeviation_;
};
BZ_NAMESPACE_END
#endif // BZ_RANDOM_NORMAL
+431
View File
@@ -0,0 +1,431 @@
// -*- C++ -*-
/***************************************************************************
* random/uniform.h Uniform IRNG wrapper class
*
* $Id$
*
* Copyright (C) 1997-2011 Todd Veldhuizen <tveldhui@acm.org>
*
* This file is a part of Blitz.
*
* Blitz is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* Blitz 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Blitz. If not, see <http://www.gnu.org/licenses/>.
*
* Suggestions: blitz-devel@lists.sourceforge.net
* Bugs: blitz-support@lists.sourceforge.net
*
* For more information, please see the Blitz++ Home Page:
* https://sourceforge.net/projects/blitz/
*
***************************************************************************/
#ifndef BZ_RANDOM_UNIFORM_H
#define BZ_RANDOM_UNIFORM_H
#include <random/default.h>
#ifndef FLT_MANT_DIG
#include <float.h>
#endif
BZ_NAMESPACE(ranlib)
/*****************************************************************************
* UniformClosedOpen generator: uniform random numbers in [0,1).
*****************************************************************************/
template<typename T = defaultType, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class UniformClosedOpen { };
// These constants are 1/2^32, 1/2^64, 1/2^96, 1/2^128
const long double norm32open = .2328306436538696289062500000000000000000E-9L;
const long double norm64open = .5421010862427522170037264004349708557129E-19L;
const long double norm96open = .1262177448353618888658765704452457967477E-28L;
const long double norm128open = .2938735877055718769921841343055614194547E-38L;
template<typename IRNG, typename stateTag>
class UniformClosedOpen<float,IRNG,stateTag>
: public IRNGWrapper<IRNG,stateTag>
{
public:
typedef float T_numtype;
UniformClosedOpen() {};
UniformClosedOpen(unsigned int i) :
IRNGWrapper<IRNG,stateTag>::IRNGWrapper(i) {};
float random()
{
#if FLT_MANT_DIG > 96
#if (FLT_MANT_DIG > 128) && !defined(BZ_IGNORE_RNG_ERRORS)
#error RNG code assumes float mantissa is <= 128 bits (not true for your platform). Use -DBZ_IGNORE_RNG_ERRORS to ignore this warning.
#endif
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
IRNG_int i3 = this->irng_.random();
IRNG_int i4 = this->irng_.random();
return i1 * norm128open + i2 * norm96open + i3 * norm64open
+ i4 * norm32open;
#elif FLT_MANT_DIG > 64
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
IRNG_int i3 = this->irng_.random();
return i1 * norm96open + i2 * norm64open + i3 * norm32open;
#elif FLT_MANT_DIG > 32
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
return i1 * norm64open + i2 * norm32open;
#else
IRNG_int i1 = this->irng_.random();
return i1 * norm32open;
#endif
}
float getUniform()
{ return random(); }
};
template<typename IRNG, typename stateTag>
class UniformClosedOpen<double,IRNG,stateTag>
: public IRNGWrapper<IRNG,stateTag>
{
public:
typedef double T_numtype;
UniformClosedOpen() {}
UniformClosedOpen(unsigned int i) :
IRNGWrapper<IRNG,stateTag>::IRNGWrapper(i) {};
double random()
{
#if DBL_MANT_DIG > 96
#if (DBL_MANT_DIG > 128) && !defined(BZ_IGNORE_RNG_ERRORS)
#error RNG code assumes double mantissa is <= 128 bits (not true for your platform). Use -DBZ_IGNORE_RNG_ERRORS to ignore this warning.
#endif
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
IRNG_int i3 = this->irng_.random();
IRNG_int i4 = this->irng_.random();
return i1 * norm128open + i2 * norm96open + i3 * norm64open
+ i4 * norm32open;
#elif DBL_MANT_DIG > 64
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
IRNG_int i3 = this->irng_.random();
return i1 * norm96open + i2 * norm64open + i3 * norm32open;
#elif DBL_MANT_DIG > 32
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
return i1 * norm64open + i2 * norm32open;
#else
IRNG_int i1 = this->irng_.random();
return i1 * norm32open;
#endif
}
double getUniform() { return random(); }
};
template<typename IRNG, typename stateTag>
class UniformClosedOpen<long double,IRNG,stateTag>
: public IRNGWrapper<IRNG,stateTag>
{
public:
typedef long double T_numtype;
UniformClosedOpen() {};
UniformClosedOpen(unsigned int i) :
IRNGWrapper<IRNG,stateTag>::IRNGWrapper(i) {};
long double random()
{
#if LDBL_MANT_DIG > 96
#if (LDBL_MANT_DIG > 128) && !defined(BZ_IGNORE_RNG_ERRORS)
#error RNG code assumes long double mantissa is <= 128 bits (not true for your platform). Use -DBZ_IGNORE_RNG_ERRORS to ignore this warning.
#endif
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
IRNG_int i3 = this->irng_.random();
IRNG_int i4 = this->irng_.random();
return i1 * norm128open + i2 * norm96open + i3 * norm64open
+ i4 * norm32open;
#elif LDBL_MANT_DIG > 64
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
IRNG_int i3 = this->irng_.random();
return i1 * norm96open + i2 * norm64open + i3 * norm32open;
#elif LDBL_MANT_DIG > 32
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
return i1 * norm64open + i2 * norm32open;
#else
IRNG_int i1 = this->irng_.random();
return i1 * norm32open;
#endif
}
long double getUniform() { return random(); }
};
// For people who don't care about open or closed: just give them
// ClosedOpen (this is the fastest).
template<class T, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class Uniform : public UniformClosedOpen<T,IRNG,stateTag>
{
public:
Uniform() {};
Uniform(unsigned int i) :
UniformClosedOpen<T,IRNG,stateTag>::UniformClosedOpen(i) {}
};
/*****************************************************************************
* UniformClosed generator: uniform random numbers in [0,1].
*****************************************************************************/
// This constant is 1/(2^32-1)
const long double norm32closed = .2328306437080797375431469961868475648078E-9L;
// These constants are 2^32/(2^64-1) and 1/(2^64-1), respectively.
const long double norm64closed1 =
.23283064365386962891887177448353618888727188481031E-9L;
const long double norm64closed2 =
.54210108624275221703311375920552804341370213034169E-19L;
// These constants are 2^64/(2^96-1), 2^32/(2^96-1), and 1/(2^96-1)
const long double norm96closed1 = .2328306436538696289062500000029387358771E-9L;
const long double norm96closed2 =
.5421010862427522170037264004418131333707E-19L;
const long double norm96closed3 =
.1262177448353618888658765704468388886588E-28L;
// These constants are 2^96/(2^128-1), 2^64/(2^128-1), 2^32/(2^128-1) and
// 1/(2^128-1).
const long double norm128clos1 = .2328306436538696289062500000000000000007E-9L;
const long double norm128clos2 = .5421010862427522170037264004349708557145E-19L;
const long double norm128clos3 = .1262177448353618888658765704452457967481E-28L;
const long double norm128clos4 = .2938735877055718769921841343055614194555E-38L;
template<typename T = double, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class UniformClosed { };
template<typename IRNG, typename stateTag>
class UniformClosed<float,IRNG,stateTag> : public IRNGWrapper<IRNG,stateTag> {
public:
typedef float T_numtype;
UniformClosed() {};
UniformClosed(unsigned int i) :
IRNGWrapper<IRNG,stateTag>::IRNGWrapper(i) {};
float random()
{
#if FLTMANT_DIG > 96
#if (FLT_MANT_DIG > 128) && !defined(BZ_IGNORE_RNG_ERRORS)
#error RNG code assumes float mantissa is <= 128 bits (not true for your platform). Use -DBZ_IGNORE_RNG_ERRORS to ignore this warning.
#endif
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
IRNG_int i3 = this->irng_.random();
IRNG_int i4 = this->irng_.random();
return i1 * norm128clos1 + i2 * norm128clos2
+ i3 * norm128clos3 + i4 * norm128clos4;
#elif FLT_MANT_DIG > 64
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
IRNG_int i3 = this->irng_.random();
return i1 * norm96closed1 + i2 * norm96closed2
+ i3 * norm96closed3;
#elif FLT_MANT_DIG > 32
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
return i1 * norm64closed1 + i2 * norm64closed2;
#else
IRNG_int i = this->irng_.random();
return i * norm32closed;
#endif
}
float getUniform()
{ return random(); }
};
template<typename IRNG, typename stateTag>
class UniformClosed<double,IRNG,stateTag> : public IRNGWrapper<IRNG,stateTag> {
public:
typedef double T_numtype;
UniformClosed() {};
UniformClosed(unsigned int i) :
IRNGWrapper<IRNG,stateTag>::IRNGWrapper(i) {};
double random()
{
#if DBL_MANT_DIG > 96
#if (DBL_MANT_DIG > 128) && !defined(BZ_IGNORE_RNG_ERRORS)
#error RNG code assumes double mantissa is <= 128 bits (not true for your platform). Use -DBZ_IGNORE_RNG_ERRORS to ignore this warning.
#endif
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
IRNG_int i3 = this->irng_.random();
IRNG_int i4 = this->irng_.random();
return i1 * norm128clos1 + i2 * norm128clos2
+ i3 * norm128clos3 + i4 * norm128clos4;
#elif DBL_MANT_DIG > 64
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
IRNG_int i3 = this->irng_.random();
return i1 * norm96closed1 + i2 * norm96closed2
+ i3 * norm96closed3;
#elif DBL_MANT_DIG > 32
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
return i1 * norm64closed1 + i2 * norm64closed2;
#else
IRNG_int i = this->irng_.random();
return i * norm32closed;
#endif
}
double getUniform()
{ return random(); }
};
template<typename IRNG, typename stateTag>
class UniformClosed<long double,IRNG,stateTag>
: public IRNGWrapper<IRNG,stateTag> {
public:
typedef long double T_numtype;
UniformClosed() {};
UniformClosed(unsigned int i) :
IRNGWrapper<IRNG,stateTag>::IRNGWrapper(i) {};
long double random()
{
#if LDBL_MANT_DIG > 96
#if (LDBL_MANT_DIG > 128) && !defined(BZ_IGNORE_RNG_ERRORS)
#error RNG code assumes long double mantissa is <= 128 bits (not true for your platform). Use -DBZ_IGNORE_RNG_ERRORS to ignore this warning.
#endif
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
IRNG_int i3 = this->irng_.random();
IRNG_int i4 = this->irng_.random();
return i1 * norm128clos1 + i2 * norm128clos2
+ i3 * norm128clos3 + i4 * norm128clos4;
#elif LDBL_MANT_DIG > 64
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
IRNG_int i3 = this->irng_.random();
return i1 * norm96closed1 + i2 * norm96closed2
+ i3 * norm96closed3;
#elif LDBL_MANT_DIG > 32
IRNG_int i1 = this->irng_.random();
IRNG_int i2 = this->irng_.random();
return i1 * norm64closed1 + i2 * norm64closed2;
#else
IRNG_int i = this->irng_.random();
return i * norm32closed;
#endif
}
long double getUniform()
{ return random(); }
};
/*****************************************************************************
* UniformOpen generator: uniform random numbers in (0,1).
*****************************************************************************/
template<typename T = double, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class UniformOpen : public UniformClosedOpen<T,IRNG,stateTag> {
public:
typedef T T_numtype;
UniformOpen() {};
UniformOpen(unsigned int i) :
UniformClosedOpen<T,IRNG,stateTag>(i) {};
T random()
{
// Turn a [0,1) into a (0,1) interval by weeding out
// any zeros.
T x;
do {
x = UniformClosedOpen<T,IRNG,stateTag>::random();
} while (x == 0.0L);
return x;
}
T getUniform()
{ return random(); }
};
/*****************************************************************************
* UniformOpenClosed generator: uniform random numbers in (0,1]
*****************************************************************************/
template<typename T = double, typename IRNG = defaultIRNG,
typename stateTag = defaultState>
class UniformOpenClosed : public UniformClosedOpen<T,IRNG,stateTag> {
public:
typedef T T_numtype;
UniformOpenClosed() {};
UniformOpenClosed(unsigned int i) :
UniformClosedOpen<T,IRNG,stateTag>(i) {};
T random()
{
// Antithetic value: taking 1-X where X is [0,1) results
// in a (0,1] distribution.
return 1.0 - UniformClosedOpen<T,IRNG,stateTag>::random();
}
T getUniform()
{ return random(); }
};
BZ_NAMESPACE_END
#endif // BZ_RANDOM_UNIFORM_H