blob: 3796c3b9bf491481c69ebb0588430b67cb5f0d22 [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 Hettinger2f726e92003-10-05 09:09:15 +00007import warnings
Raymond Hettinger3dd990c2003-01-05 09:20:06 +00008from math import log, exp, sqrt, pi
Raymond Hettinger7b0cf762003-01-17 17:23:23 +00009from sets import Set
Raymond Hettinger40f62172002-12-29 23:03:38 +000010from test import test_support
Tim Peters46c04e12002-05-05 20:40:00 +000011
Raymond Hettinger40f62172002-12-29 23:03:38 +000012class TestBasicOps(unittest.TestCase):
13 # Superclass with tests common to all generators.
14 # Subclasses must arrange for self.gen to retrieve the Random instance
15 # to be tested.
Tim Peters46c04e12002-05-05 20:40:00 +000016
Raymond Hettinger40f62172002-12-29 23:03:38 +000017 def randomlist(self, n):
18 """Helper function to make a list of random numbers"""
19 return [self.gen.random() for i in xrange(n)]
Tim Peters46c04e12002-05-05 20:40:00 +000020
Raymond Hettinger40f62172002-12-29 23:03:38 +000021 def test_autoseed(self):
22 self.gen.seed()
23 state1 = self.gen.getstate()
Raymond Hettinger3081d592003-08-09 18:30:57 +000024 time.sleep(0.1)
Raymond Hettinger40f62172002-12-29 23:03:38 +000025 self.gen.seed() # diffent seeds at different times
26 state2 = self.gen.getstate()
27 self.assertNotEqual(state1, state2)
Tim Peters46c04e12002-05-05 20:40:00 +000028
Raymond Hettinger40f62172002-12-29 23:03:38 +000029 def test_saverestore(self):
30 N = 1000
31 self.gen.seed()
32 state = self.gen.getstate()
33 randseq = self.randomlist(N)
34 self.gen.setstate(state) # should regenerate the same sequence
35 self.assertEqual(randseq, self.randomlist(N))
36
37 def test_seedargs(self):
38 for arg in [None, 0, 0L, 1, 1L, -1, -1L, 10**20, -(10**20),
39 3.14, 1+2j, 'a', tuple('abc')]:
40 self.gen.seed(arg)
41 for arg in [range(3), dict(one=1)]:
42 self.assertRaises(TypeError, self.gen.seed, arg)
43
44 def test_jumpahead(self):
45 self.gen.seed()
46 state1 = self.gen.getstate()
47 self.gen.jumpahead(100)
48 state2 = self.gen.getstate() # s/b distinct from state1
49 self.assertNotEqual(state1, state2)
50 self.gen.jumpahead(100)
51 state3 = self.gen.getstate() # s/b distinct from state2
52 self.assertNotEqual(state2, state3)
53
54 self.assertRaises(TypeError, self.gen.jumpahead) # needs an arg
55 self.assertRaises(TypeError, self.gen.jumpahead, "ick") # wrong type
56 self.assertRaises(TypeError, self.gen.jumpahead, 2.3) # wrong type
57 self.assertRaises(TypeError, self.gen.jumpahead, 2, 3) # too many
58
59 def test_sample(self):
60 # For the entire allowable range of 0 <= k <= N, validate that
61 # the sample is of the correct length and contains only unique items
62 N = 100
63 population = xrange(N)
64 for k in xrange(N+1):
65 s = self.gen.sample(population, k)
66 self.assertEqual(len(s), k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +000067 uniq = Set(s)
Raymond Hettinger40f62172002-12-29 23:03:38 +000068 self.assertEqual(len(uniq), k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +000069 self.failUnless(uniq <= Set(population))
Raymond Hettinger8ec78812003-01-04 05:55:11 +000070 self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
Raymond Hettinger40f62172002-12-29 23:03:38 +000071
Raymond Hettinger7b0cf762003-01-17 17:23:23 +000072 def test_sample_distribution(self):
73 # For the entire allowable range of 0 <= k <= N, validate that
74 # sample generates all possible permutations
75 n = 5
76 pop = range(n)
77 trials = 10000 # large num prevents false negatives without slowing normal case
78 def factorial(n):
Raymond Hettinger105b0842003-02-04 05:47:30 +000079 return reduce(int.__mul__, xrange(1, n), 1)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +000080 for k in xrange(n):
81 expected = factorial(n) / factorial(n-k)
82 perms = {}
83 for i in xrange(trials):
84 perms[tuple(self.gen.sample(pop, k))] = None
85 if len(perms) == expected:
86 break
87 else:
88 self.fail()
89
Raymond Hettinger66d09f12003-09-06 04:25:54 +000090 def test_sample_inputs(self):
91 # SF bug #801342 -- population can be any iterable defining __len__()
92 from sets import Set
93 self.gen.sample(Set(range(20)), 2)
94 self.gen.sample(range(20), 2)
95 self.gen.sample(xrange(20), 2)
96 self.gen.sample(dict.fromkeys('abcdefghijklmnopqrst'), 2)
97 self.gen.sample(str('abcdefghijklmnopqrst'), 2)
98 self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
99
Raymond Hettinger40f62172002-12-29 23:03:38 +0000100 def test_gauss(self):
101 # Ensure that the seed() method initializes all the hidden state. In
102 # particular, through 2.2.1 it failed to reset a piece of state used
103 # by (and only by) the .gauss() method.
104
105 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
106 self.gen.seed(seed)
107 x1 = self.gen.random()
108 y1 = self.gen.gauss(0, 1)
109
110 self.gen.seed(seed)
111 x2 = self.gen.random()
112 y2 = self.gen.gauss(0, 1)
113
114 self.assertEqual(x1, x2)
115 self.assertEqual(y1, y2)
116
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000117 def test_pickling(self):
118 state = pickle.dumps(self.gen)
119 origseq = [self.gen.random() for i in xrange(10)]
120 newgen = pickle.loads(state)
121 restoredseq = [newgen.random() for i in xrange(10)]
122 self.assertEqual(origseq, restoredseq)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000123
124class WichmannHill_TestBasicOps(TestBasicOps):
125 gen = random.WichmannHill()
126
127 def test_strong_jumpahead(self):
128 # tests that jumpahead(n) semantics correspond to n calls to random()
129 N = 1000
130 s = self.gen.getstate()
131 self.gen.jumpahead(N)
132 r1 = self.gen.random()
133 # now do it the slow way
134 self.gen.setstate(s)
135 for i in xrange(N):
136 self.gen.random()
137 r2 = self.gen.random()
138 self.assertEqual(r1, r2)
139
140 def test_gauss_with_whseed(self):
141 # Ensure that the seed() method initializes all the hidden state. In
142 # particular, through 2.2.1 it failed to reset a piece of state used
143 # by (and only by) the .gauss() method.
144
145 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
146 self.gen.whseed(seed)
147 x1 = self.gen.random()
148 y1 = self.gen.gauss(0, 1)
149
150 self.gen.whseed(seed)
151 x2 = self.gen.random()
152 y2 = self.gen.gauss(0, 1)
153
154 self.assertEqual(x1, x2)
155 self.assertEqual(y1, y2)
156
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000157 def test_bigrand(self):
158 # Verify warnings are raised when randrange is too large for random()
159 oldfilters = warnings.filters[:]
160 warnings.filterwarnings("error", "Underlying random")
161 self.assertRaises(UserWarning, self.gen.randrange, 2**60)
162 warnings.filters[:] = oldfilters
163
Raymond Hettinger40f62172002-12-29 23:03:38 +0000164class MersenneTwister_TestBasicOps(TestBasicOps):
165 gen = random.Random()
166
167 def test_referenceImplementation(self):
168 # Compare the python implementation with results from the original
169 # code. Create 2000 53-bit precision random floats. Compare only
170 # the last ten entries to show that the independent implementations
171 # are tracking. Here is the main() function needed to create the
172 # list of expected random numbers:
173 # void main(void){
174 # int i;
175 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
176 # init_by_array(init, length);
177 # for (i=0; i<2000; i++) {
178 # printf("%.15f ", genrand_res53());
179 # if (i%5==4) printf("\n");
180 # }
181 # }
182 expected = [0.45839803073713259,
183 0.86057815201978782,
184 0.92848331726782152,
185 0.35932681119782461,
186 0.081823493762449573,
187 0.14332226470169329,
188 0.084297823823520024,
189 0.53814864671831453,
190 0.089215024911993401,
191 0.78486196105372907]
192
193 self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96))
194 actual = self.randomlist(2000)[-10:]
195 for a, e in zip(actual, expected):
196 self.assertAlmostEqual(a,e,places=14)
197
198 def test_strong_reference_implementation(self):
199 # Like test_referenceImplementation, but checks for exact bit-level
200 # equality. This should pass on any box where C double contains
201 # at least 53 bits of precision (the underlying algorithm suffers
202 # no rounding errors -- all results are exact).
203 from math import ldexp
204
205 expected = [0x0eab3258d2231fL,
206 0x1b89db315277a5L,
207 0x1db622a5518016L,
208 0x0b7f9af0d575bfL,
209 0x029e4c4db82240L,
210 0x04961892f5d673L,
211 0x02b291598e4589L,
212 0x11388382c15694L,
213 0x02dad977c9e1feL,
214 0x191d96d4d334c6L]
215
216 self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96))
217 actual = self.randomlist(2000)[-10:]
218 for a, e in zip(actual, expected):
219 self.assertEqual(long(ldexp(a, 53)), e)
220
221 def test_long_seed(self):
222 # This is most interesting to run in debug mode, just to make sure
223 # nothing blows up. Under the covers, a dynamically resized array
224 # is allocated, consuming space proportional to the number of bits
225 # in the seed. Unfortunately, that's a quadratic-time algorithm,
226 # so don't make this horribly big.
227 seed = (1L << (10000 * 8)) - 1 # about 10K bytes
228 self.gen.seed(seed)
229
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000230 def test_53_bits_per_float(self):
231 # This should pass whenever a C double has 53 bit precision.
232 span = 2 ** 53
233 cum = 0
234 for i in xrange(100):
235 cum |= int(self.gen.random() * span)
236 self.assertEqual(cum, span-1)
237
238 def test_bigrand(self):
239 # The randrange routine should build-up the required number of bits
240 # in stages so that all bit positions are active.
241 span = 2 ** 500
242 cum = 0
243 for i in xrange(100):
244 r = self.gen.randrange(span)
245 self.assert_(0 <= r < span)
246 cum |= r
247 self.assertEqual(cum, span-1)
248
249 def test_bigrand_ranges(self):
250 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
251 start = self.gen.randrange(2 ** i)
252 stop = self.gen.randrange(2 ** (i-2))
253 if stop <= start:
254 return
255 self.assert_(start <= self.gen.randrange(start, stop) < stop)
256
257 def test_rangelimits(self):
258 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
259 self.assertEqual(Set(range(start,stop)),
260 Set([self.gen.randrange(start,stop) for i in xrange(100)]))
261
262 def test_genrandbits(self):
263 # Verify cross-platform repeatability
264 self.gen.seed(1234567)
265 self.assertEqual(self.gen.getrandbits(100),
266 97904845777343510404718956115L)
267 # Verify ranges
268 for k in xrange(1, 1000):
269 self.assert_(0 <= self.gen.getrandbits(k) < 2**k)
270
271 # Verify all bits active
272 getbits = self.gen.getrandbits
273 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
274 cum = 0
275 for i in xrange(100):
276 cum |= getbits(span)
277 self.assertEqual(cum, 2**span-1)
278
279 def test_randbelow_logic(self, _log=log, int=int):
280 # check bitcount transition points: 2**i and 2**(i+1)-1
281 # show that: k = int(1.001 + _log(n, 2))
282 # is equal to or one greater than the number of bits in n
283 for i in xrange(1, 1000):
284 n = 1L << i # check an exact power of two
285 numbits = i+1
286 k = int(1.00001 + _log(n, 2))
287 self.assertEqual(k, numbits)
288 self.assert_(n == 2**(k-1))
289
290 n += n - 1 # check 1 below the next power of two
291 k = int(1.00001 + _log(n, 2))
292 self.assert_(k in [numbits, numbits+1])
293 self.assert_(2**k > n > 2**(k-2))
294
295 n -= n >> 15 # check a little farther below the next power of two
296 k = int(1.00001 + _log(n, 2))
297 self.assertEqual(k, numbits) # note the stronger assertion
298 self.assert_(2**k > n > 2**(k-1)) # note the stronger assertion
299
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000300_gammacoeff = (0.9999999999995183, 676.5203681218835, -1259.139216722289,
301 771.3234287757674, -176.6150291498386, 12.50734324009056,
302 -0.1385710331296526, 0.9934937113930748e-05, 0.1659470187408462e-06)
303
304def gamma(z, cof=_gammacoeff, g=7):
305 z -= 1.0
306 sum = cof[0]
307 for i in xrange(1,len(cof)):
308 sum += cof[i] / (z+i)
309 z += 0.5
310 return (z+g)**z / exp(z+g) * sqrt(2*pi) * sum
311
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000312class TestDistributions(unittest.TestCase):
313 def test_zeroinputs(self):
314 # Verify that distributions can handle a series of zero inputs'
315 g = random.Random()
316 x = [g.random() for i in xrange(50)] + [0.0]*5
317 g.random = x[:].pop; g.uniform(1,10)
318 g.random = x[:].pop; g.paretovariate(1.0)
319 g.random = x[:].pop; g.expovariate(1.0)
320 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
321 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
322 g.random = x[:].pop; g.gauss(0.0, 1.0)
323 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
324 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
325 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
326 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
327 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
328 g.random = x[:].pop; g.betavariate(3.0, 3.0)
329
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000330 def test_avg_std(self):
331 # Use integration to test distribution average and standard deviation.
332 # Only works for distributions which do not consume variates in pairs
333 g = random.Random()
334 N = 5000
335 x = [i/float(N) for i in xrange(1,N)]
336 for variate, args, mu, sigmasqrd in [
337 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
338 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
339 (g.paretovariate, (5.0,), 5.0/(5.0-1),
340 5.0/((5.0-1)**2*(5.0-2))),
341 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
342 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
343 g.random = x[:].pop
344 y = []
345 for i in xrange(len(x)):
346 try:
347 y.append(variate(*args))
348 except IndexError:
349 pass
350 s1 = s2 = 0
351 for e in y:
352 s1 += e
353 s2 += (e - mu) ** 2
354 N = len(y)
355 self.assertAlmostEqual(s1/N, mu, 2)
356 self.assertAlmostEqual(s2/(N-1), sigmasqrd, 2)
357
Raymond Hettinger40f62172002-12-29 23:03:38 +0000358class TestModule(unittest.TestCase):
359 def testMagicConstants(self):
360 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
361 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
362 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
363 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
364
365 def test__all__(self):
366 # tests validity but not completeness of the __all__ list
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000367 self.failUnless(Set(random.__all__) <= Set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000368
Raymond Hettinger105b0842003-02-04 05:47:30 +0000369def test_main(verbose=None):
Raymond Hettinger27922ee2003-05-03 03:38:01 +0000370 testclasses = (WichmannHill_TestBasicOps,
Raymond Hettinger40f62172002-12-29 23:03:38 +0000371 MersenneTwister_TestBasicOps,
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000372 TestDistributions,
Raymond Hettinger27922ee2003-05-03 03:38:01 +0000373 TestModule)
374 test_support.run_unittest(*testclasses)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000375
Raymond Hettinger105b0842003-02-04 05:47:30 +0000376 # verify reference counting
377 import sys
378 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger320a1b02003-05-02 22:44:59 +0000379 counts = [None] * 5
380 for i in xrange(len(counts)):
Raymond Hettinger27922ee2003-05-03 03:38:01 +0000381 test_support.run_unittest(*testclasses)
Raymond Hettinger320a1b02003-05-02 22:44:59 +0000382 counts[i] = sys.gettotalrefcount()
Raymond Hettinger105b0842003-02-04 05:47:30 +0000383 print counts
384
Raymond Hettinger40f62172002-12-29 23:03:38 +0000385if __name__ == "__main__":
Raymond Hettinger105b0842003-02-04 05:47:30 +0000386 test_main(verbose=True)