random.icc
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040 namespace Gecode { namespace Support {
00041
00049 template<unsigned int m, unsigned int a, unsigned int q, unsigned int r>
00050 class LinearCongruentialGenerator {
00051 private:
00053 static const unsigned int max = 1UL<<31;
00055 unsigned int s;
00057 unsigned int next(void);
00058 public:
00060 void seed(unsigned int _s);
00062 LinearCongruentialGenerator(unsigned int _s = 1);
00064 unsigned int seed(void) const;
00066 unsigned int operator()(unsigned int n);
00067 };
00068
00069 template<unsigned int m, unsigned int a, unsigned int q, unsigned int r>
00070 forceinline unsigned int
00071 LinearCongruentialGenerator<m,a,q,r>::next(void) {
00072 s = a*(s%q) - r*(s/q);
00073 unsigned int res = s;
00074 if (s==0) s = 1;
00075 return res;
00076 }
00077 template<unsigned int m, unsigned int a, unsigned int q, unsigned int r>
00078 forceinline void
00079 LinearCongruentialGenerator<m,a,q,r>::seed(unsigned int _s) {
00080 s = _s % m;
00081 if (s == 0) s = 1;
00082 }
00083 template<unsigned int m, unsigned int a, unsigned int q, unsigned int r>
00084 forceinline
00085 LinearCongruentialGenerator<m,a,q,r>::
00086 LinearCongruentialGenerator(unsigned int _s) {
00087 seed(_s);
00088 }
00089 template<unsigned int m, unsigned int a, unsigned int q, unsigned int r>
00090 forceinline unsigned int
00091 LinearCongruentialGenerator<m,a,q,r>::seed(void) const {
00092 return s;
00093 }
00094 template<unsigned int m, unsigned int a, unsigned int q, unsigned int r>
00095 forceinline unsigned int
00096 LinearCongruentialGenerator<m,a,q,r>::operator()(unsigned int n) {
00097 unsigned int x1 = next() & ((1<<16)-1);
00098 unsigned int x2 = next() & ((1<<16)-1);
00099 if (n < 2) return 0;
00100 double d = static_cast<double>(((x1<<16) | x2) % max) / max;
00101 unsigned int val = static_cast<unsigned int>(n * d);
00102 return (val < n) ? val : (n-1);
00103 }
00104
00105
00116 typedef LinearCongruentialGenerator<2147483647, 48271, 44488, 3399>
00117 RandomGenerator;
00118
00119 }}
00120
00121