blob: fbd418457a68ba185f0c53aa74a6518b79d37482 [file] [log] [blame]
Raymond Hettinger40f62172002-12-29 23:03:38 +00001#!/usr/bin/env python
2
3import unittest
Tim Peters46c04e12002-05-05 20:40:00 +00004import random
Raymond Hettinger40f62172002-12-29 23:03:38 +00005import time
Raymond Hettinger5f078ff2003-06-24 20:29:04 +00006import pickle
Raymond Hettinger3dd990c2003-01-05 09:20:06 +00007from math import log, exp, sqrt, pi
Raymond Hettinger7b0cf762003-01-17 17:23:23 +00008from sets import Set
Raymond Hettinger40f62172002-12-29 23:03:38 +00009from test import test_support
Tim Peters46c04e12002-05-05 20:40:00 +000010
Raymond Hettinger40f62172002-12-29 23:03:38 +000011class TestBasicOps(unittest.TestCase):
12 # Superclass with tests common to all generators.
13 # Subclasses must arrange for self.gen to retrieve the Random instance
14 # to be tested.
Tim Peters46c04e12002-05-05 20:40:00 +000015
Raymond Hettinger40f62172002-12-29 23:03:38 +000016 def randomlist(self, n):
17 """Helper function to make a list of random numbers"""
18 return [self.gen.random() for i in xrange(n)]
Tim Peters46c04e12002-05-05 20:40:00 +000019
Raymond Hettinger40f62172002-12-29 23:03:38 +000020 def test_autoseed(self):
21 self.gen.seed()
22 state1 = self.gen.getstate()
Raymond Hettinger3081d592003-08-09 18:30:57 +000023 time.sleep(0.1)
Raymond Hettinger40f62172002-12-29 23:03:38 +000024 self.gen.seed() # diffent seeds at different times
25 state2 = self.gen.getstate()
26 self.assertNotEqual(state1, state2)
Tim Peters46c04e12002-05-05 20:40:00 +000027
Raymond Hettinger40f62172002-12-29 23:03:38 +000028 def test_saverestore(self):
29 N = 1000
30 self.gen.seed()
31 state = self.gen.getstate()
32 randseq = self.randomlist(N)
33 self.gen.setstate(state) # should regenerate the same sequence
34 self.assertEqual(randseq, self.randomlist(N))
35
36 def test_seedargs(self):
37 for arg in [None, 0, 0L, 1, 1L, -1, -1L, 10**20, -(10**20),
38 3.14, 1+2j, 'a', tuple('abc')]:
39 self.gen.seed(arg)
40 for arg in [range(3), dict(one=1)]:
41 self.assertRaises(TypeError, self.gen.seed, arg)
42
43 def test_jumpahead(self):
44 self.gen.seed()
45 state1 = self.gen.getstate()
46 self.gen.jumpahead(100)
47 state2 = self.gen.getstate() # s/b distinct from state1
48 self.assertNotEqual(state1, state2)
49 self.gen.jumpahead(100)
50 state3 = self.gen.getstate() # s/b distinct from state2
51 self.assertNotEqual(state2, state3)
52
53 self.assertRaises(TypeError, self.gen.jumpahead) # needs an arg
54 self.assertRaises(TypeError, self.gen.jumpahead, "ick") # wrong type
55 self.assertRaises(TypeError, self.gen.jumpahead, 2.3) # wrong type
56 self.assertRaises(TypeError, self.gen.jumpahead, 2, 3) # too many
57
58 def test_sample(self):
59 # For the entire allowable range of 0 <= k <= N, validate that
60 # the sample is of the correct length and contains only unique items
61 N = 100
62 population = xrange(N)
63 for k in xrange(N+1):
64 s = self.gen.sample(population, k)
65 self.assertEqual(len(s), k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +000066 uniq = Set(s)
Raymond Hettinger40f62172002-12-29 23:03:38 +000067 self.assertEqual(len(uniq), k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +000068 self.failUnless(uniq <= Set(population))
Raymond Hettinger8ec78812003-01-04 05:55:11 +000069 self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
Raymond Hettinger40f62172002-12-29 23:03:38 +000070
Raymond Hettinger7b0cf762003-01-17 17:23:23 +000071 def test_sample_distribution(self):
72 # For the entire allowable range of 0 <= k <= N, validate that
73 # sample generates all possible permutations
74 n = 5
75 pop = range(n)
76 trials = 10000 # large num prevents false negatives without slowing normal case
77 def factorial(n):
Raymond Hettinger105b0842003-02-04 05:47:30 +000078 return reduce(int.__mul__, xrange(1, n), 1)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +000079 for k in xrange(n):
80 expected = factorial(n) / factorial(n-k)
81 perms = {}
82 for i in xrange(trials):
83 perms[tuple(self.gen.sample(pop, k))] = None
84 if len(perms) == expected:
85 break
86 else:
87 self.fail()
88
Raymond Hettinger66d09f12003-09-06 04:25:54 +000089 def test_sample_inputs(self):
90 # SF bug #801342 -- population can be any iterable defining __len__()
91 from sets import Set
92 self.gen.sample(Set(range(20)), 2)
93 self.gen.sample(range(20), 2)
94 self.gen.sample(xrange(20), 2)
95 self.gen.sample(dict.fromkeys('abcdefghijklmnopqrst'), 2)
96 self.gen.sample(str('abcdefghijklmnopqrst'), 2)
97 self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
98
Raymond Hettinger40f62172002-12-29 23:03:38 +000099 def test_gauss(self):
100 # Ensure that the seed() method initializes all the hidden state. In
101 # particular, through 2.2.1 it failed to reset a piece of state used
102 # by (and only by) the .gauss() method.
103
104 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
105 self.gen.seed(seed)
106 x1 = self.gen.random()
107 y1 = self.gen.gauss(0, 1)
108
109 self.gen.seed(seed)
110 x2 = self.gen.random()
111 y2 = self.gen.gauss(0, 1)
112
113 self.assertEqual(x1, x2)
114 self.assertEqual(y1, y2)
115
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000116 def test_pickling(self):
117 state = pickle.dumps(self.gen)
118 origseq = [self.gen.random() for i in xrange(10)]
119 newgen = pickle.loads(state)
120 restoredseq = [newgen.random() for i in xrange(10)]
121 self.assertEqual(origseq, restoredseq)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000122
123class WichmannHill_TestBasicOps(TestBasicOps):
124 gen = random.WichmannHill()
125
126 def test_strong_jumpahead(self):
127 # tests that jumpahead(n) semantics correspond to n calls to random()
128 N = 1000
129 s = self.gen.getstate()
130 self.gen.jumpahead(N)
131 r1 = self.gen.random()
132 # now do it the slow way
133 self.gen.setstate(s)
134 for i in xrange(N):
135 self.gen.random()
136 r2 = self.gen.random()
137 self.assertEqual(r1, r2)
138
139 def test_gauss_with_whseed(self):
140 # Ensure that the seed() method initializes all the hidden state. In
141 # particular, through 2.2.1 it failed to reset a piece of state used
142 # by (and only by) the .gauss() method.
143
144 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
145 self.gen.whseed(seed)
146 x1 = self.gen.random()
147 y1 = self.gen.gauss(0, 1)
148
149 self.gen.whseed(seed)
150 x2 = self.gen.random()
151 y2 = self.gen.gauss(0, 1)
152
153 self.assertEqual(x1, x2)
154 self.assertEqual(y1, y2)
155
156class MersenneTwister_TestBasicOps(TestBasicOps):
157 gen = random.Random()
158
159 def test_referenceImplementation(self):
160 # Compare the python implementation with results from the original
161 # code. Create 2000 53-bit precision random floats. Compare only
162 # the last ten entries to show that the independent implementations
163 # are tracking. Here is the main() function needed to create the
164 # list of expected random numbers:
165 # void main(void){
166 # int i;
167 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
168 # init_by_array(init, length);
169 # for (i=0; i<2000; i++) {
170 # printf("%.15f ", genrand_res53());
171 # if (i%5==4) printf("\n");
172 # }
173 # }
174 expected = [0.45839803073713259,
175 0.86057815201978782,
176 0.92848331726782152,
177 0.35932681119782461,
178 0.081823493762449573,
179 0.14332226470169329,
180 0.084297823823520024,
181 0.53814864671831453,
182 0.089215024911993401,
183 0.78486196105372907]
184
185 self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96))
186 actual = self.randomlist(2000)[-10:]
187 for a, e in zip(actual, expected):
188 self.assertAlmostEqual(a,e,places=14)
189
190 def test_strong_reference_implementation(self):
191 # Like test_referenceImplementation, but checks for exact bit-level
192 # equality. This should pass on any box where C double contains
193 # at least 53 bits of precision (the underlying algorithm suffers
194 # no rounding errors -- all results are exact).
195 from math import ldexp
196
197 expected = [0x0eab3258d2231fL,
198 0x1b89db315277a5L,
199 0x1db622a5518016L,
200 0x0b7f9af0d575bfL,
201 0x029e4c4db82240L,
202 0x04961892f5d673L,
203 0x02b291598e4589L,
204 0x11388382c15694L,
205 0x02dad977c9e1feL,
206 0x191d96d4d334c6L]
207
208 self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96))
209 actual = self.randomlist(2000)[-10:]
210 for a, e in zip(actual, expected):
211 self.assertEqual(long(ldexp(a, 53)), e)
212
213 def test_long_seed(self):
214 # This is most interesting to run in debug mode, just to make sure
215 # nothing blows up. Under the covers, a dynamically resized array
216 # is allocated, consuming space proportional to the number of bits
217 # in the seed. Unfortunately, that's a quadratic-time algorithm,
218 # so don't make this horribly big.
219 seed = (1L << (10000 * 8)) - 1 # about 10K bytes
220 self.gen.seed(seed)
221
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000222_gammacoeff = (0.9999999999995183, 676.5203681218835, -1259.139216722289,
223 771.3234287757674, -176.6150291498386, 12.50734324009056,
224 -0.1385710331296526, 0.9934937113930748e-05, 0.1659470187408462e-06)
225
226def gamma(z, cof=_gammacoeff, g=7):
227 z -= 1.0
228 sum = cof[0]
229 for i in xrange(1,len(cof)):
230 sum += cof[i] / (z+i)
231 z += 0.5
232 return (z+g)**z / exp(z+g) * sqrt(2*pi) * sum
233
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000234class TestDistributions(unittest.TestCase):
235 def test_zeroinputs(self):
236 # Verify that distributions can handle a series of zero inputs'
237 g = random.Random()
238 x = [g.random() for i in xrange(50)] + [0.0]*5
239 g.random = x[:].pop; g.uniform(1,10)
240 g.random = x[:].pop; g.paretovariate(1.0)
241 g.random = x[:].pop; g.expovariate(1.0)
242 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
243 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
244 g.random = x[:].pop; g.gauss(0.0, 1.0)
245 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
246 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
247 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
248 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
249 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
250 g.random = x[:].pop; g.betavariate(3.0, 3.0)
251
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000252 def test_avg_std(self):
253 # Use integration to test distribution average and standard deviation.
254 # Only works for distributions which do not consume variates in pairs
255 g = random.Random()
256 N = 5000
257 x = [i/float(N) for i in xrange(1,N)]
258 for variate, args, mu, sigmasqrd in [
259 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
260 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
261 (g.paretovariate, (5.0,), 5.0/(5.0-1),
262 5.0/((5.0-1)**2*(5.0-2))),
263 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
264 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
265 g.random = x[:].pop
266 y = []
267 for i in xrange(len(x)):
268 try:
269 y.append(variate(*args))
270 except IndexError:
271 pass
272 s1 = s2 = 0
273 for e in y:
274 s1 += e
275 s2 += (e - mu) ** 2
276 N = len(y)
277 self.assertAlmostEqual(s1/N, mu, 2)
278 self.assertAlmostEqual(s2/(N-1), sigmasqrd, 2)
279
Raymond Hettinger40f62172002-12-29 23:03:38 +0000280class TestModule(unittest.TestCase):
281 def testMagicConstants(self):
282 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
283 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
284 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
285 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
286
287 def test__all__(self):
288 # tests validity but not completeness of the __all__ list
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000289 self.failUnless(Set(random.__all__) <= Set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000290
Raymond Hettinger105b0842003-02-04 05:47:30 +0000291def test_main(verbose=None):
Raymond Hettinger27922ee2003-05-03 03:38:01 +0000292 testclasses = (WichmannHill_TestBasicOps,
Raymond Hettinger40f62172002-12-29 23:03:38 +0000293 MersenneTwister_TestBasicOps,
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000294 TestDistributions,
Raymond Hettinger27922ee2003-05-03 03:38:01 +0000295 TestModule)
296 test_support.run_unittest(*testclasses)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000297
Raymond Hettinger105b0842003-02-04 05:47:30 +0000298 # verify reference counting
299 import sys
300 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger320a1b02003-05-02 22:44:59 +0000301 counts = [None] * 5
302 for i in xrange(len(counts)):
Raymond Hettinger27922ee2003-05-03 03:38:01 +0000303 test_support.run_unittest(*testclasses)
Raymond Hettinger320a1b02003-05-02 22:44:59 +0000304 counts[i] = sys.gettotalrefcount()
Raymond Hettinger105b0842003-02-04 05:47:30 +0000305 print counts
306
Raymond Hettinger40f62172002-12-29 23:03:38 +0000307if __name__ == "__main__":
Raymond Hettinger105b0842003-02-04 05:47:30 +0000308 test_main(verbose=True)