blob: 8d005a25a967056748e9386f193ddcd52954fefd [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 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 Hettingera690a992003-11-16 16:17:49 +000066 uniq = set(s)
Raymond Hettinger40f62172002-12-29 23:03:38 +000067 self.assertEqual(len(uniq), k)
Raymond Hettingera690a992003-11-16 16:17:49 +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__()
Raymond Hettingera690a992003-11-16 16:17:49 +000091 self.gen.sample(set(range(20)), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +000092 self.gen.sample(range(20), 2)
93 self.gen.sample(xrange(20), 2)
94 self.gen.sample(dict.fromkeys('abcdefghijklmnopqrst'), 2)
95 self.gen.sample(str('abcdefghijklmnopqrst'), 2)
96 self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
97
Raymond Hettinger40f62172002-12-29 23:03:38 +000098 def test_gauss(self):
99 # Ensure that the seed() method initializes all the hidden state. In
100 # particular, through 2.2.1 it failed to reset a piece of state used
101 # by (and only by) the .gauss() method.
102
103 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
104 self.gen.seed(seed)
105 x1 = self.gen.random()
106 y1 = self.gen.gauss(0, 1)
107
108 self.gen.seed(seed)
109 x2 = self.gen.random()
110 y2 = self.gen.gauss(0, 1)
111
112 self.assertEqual(x1, x2)
113 self.assertEqual(y1, y2)
114
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000115 def test_pickling(self):
116 state = pickle.dumps(self.gen)
117 origseq = [self.gen.random() for i in xrange(10)]
118 newgen = pickle.loads(state)
119 restoredseq = [newgen.random() for i in xrange(10)]
120 self.assertEqual(origseq, restoredseq)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000121
122class WichmannHill_TestBasicOps(TestBasicOps):
123 gen = random.WichmannHill()
124
125 def test_strong_jumpahead(self):
126 # tests that jumpahead(n) semantics correspond to n calls to random()
127 N = 1000
128 s = self.gen.getstate()
129 self.gen.jumpahead(N)
130 r1 = self.gen.random()
131 # now do it the slow way
132 self.gen.setstate(s)
133 for i in xrange(N):
134 self.gen.random()
135 r2 = self.gen.random()
136 self.assertEqual(r1, r2)
137
138 def test_gauss_with_whseed(self):
139 # Ensure that the seed() method initializes all the hidden state. In
140 # particular, through 2.2.1 it failed to reset a piece of state used
141 # by (and only by) the .gauss() method.
142
143 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
144 self.gen.whseed(seed)
145 x1 = self.gen.random()
146 y1 = self.gen.gauss(0, 1)
147
148 self.gen.whseed(seed)
149 x2 = self.gen.random()
150 y2 = self.gen.gauss(0, 1)
151
152 self.assertEqual(x1, x2)
153 self.assertEqual(y1, y2)
154
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000155 def test_bigrand(self):
156 # Verify warnings are raised when randrange is too large for random()
157 oldfilters = warnings.filters[:]
158 warnings.filterwarnings("error", "Underlying random")
159 self.assertRaises(UserWarning, self.gen.randrange, 2**60)
160 warnings.filters[:] = oldfilters
161
Raymond Hettinger40f62172002-12-29 23:03:38 +0000162class MersenneTwister_TestBasicOps(TestBasicOps):
163 gen = random.Random()
164
165 def test_referenceImplementation(self):
166 # Compare the python implementation with results from the original
167 # code. Create 2000 53-bit precision random floats. Compare only
168 # the last ten entries to show that the independent implementations
169 # are tracking. Here is the main() function needed to create the
170 # list of expected random numbers:
171 # void main(void){
172 # int i;
173 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
174 # init_by_array(init, length);
175 # for (i=0; i<2000; i++) {
176 # printf("%.15f ", genrand_res53());
177 # if (i%5==4) printf("\n");
178 # }
179 # }
180 expected = [0.45839803073713259,
181 0.86057815201978782,
182 0.92848331726782152,
183 0.35932681119782461,
184 0.081823493762449573,
185 0.14332226470169329,
186 0.084297823823520024,
187 0.53814864671831453,
188 0.089215024911993401,
189 0.78486196105372907]
190
191 self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96))
192 actual = self.randomlist(2000)[-10:]
193 for a, e in zip(actual, expected):
194 self.assertAlmostEqual(a,e,places=14)
195
196 def test_strong_reference_implementation(self):
197 # Like test_referenceImplementation, but checks for exact bit-level
198 # equality. This should pass on any box where C double contains
199 # at least 53 bits of precision (the underlying algorithm suffers
200 # no rounding errors -- all results are exact).
201 from math import ldexp
202
203 expected = [0x0eab3258d2231fL,
204 0x1b89db315277a5L,
205 0x1db622a5518016L,
206 0x0b7f9af0d575bfL,
207 0x029e4c4db82240L,
208 0x04961892f5d673L,
209 0x02b291598e4589L,
210 0x11388382c15694L,
211 0x02dad977c9e1feL,
212 0x191d96d4d334c6L]
213
214 self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96))
215 actual = self.randomlist(2000)[-10:]
216 for a, e in zip(actual, expected):
217 self.assertEqual(long(ldexp(a, 53)), e)
218
219 def test_long_seed(self):
220 # This is most interesting to run in debug mode, just to make sure
221 # nothing blows up. Under the covers, a dynamically resized array
222 # is allocated, consuming space proportional to the number of bits
223 # in the seed. Unfortunately, that's a quadratic-time algorithm,
224 # so don't make this horribly big.
225 seed = (1L << (10000 * 8)) - 1 # about 10K bytes
226 self.gen.seed(seed)
227
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000228 def test_53_bits_per_float(self):
229 # This should pass whenever a C double has 53 bit precision.
230 span = 2 ** 53
231 cum = 0
232 for i in xrange(100):
233 cum |= int(self.gen.random() * span)
234 self.assertEqual(cum, span-1)
235
236 def test_bigrand(self):
237 # The randrange routine should build-up the required number of bits
238 # in stages so that all bit positions are active.
239 span = 2 ** 500
240 cum = 0
241 for i in xrange(100):
242 r = self.gen.randrange(span)
243 self.assert_(0 <= r < span)
244 cum |= r
245 self.assertEqual(cum, span-1)
246
247 def test_bigrand_ranges(self):
248 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
249 start = self.gen.randrange(2 ** i)
250 stop = self.gen.randrange(2 ** (i-2))
251 if stop <= start:
252 return
253 self.assert_(start <= self.gen.randrange(start, stop) < stop)
254
255 def test_rangelimits(self):
256 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
Raymond Hettingera690a992003-11-16 16:17:49 +0000257 self.assertEqual(set(range(start,stop)),
258 set([self.gen.randrange(start,stop) for i in xrange(100)]))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000259
260 def test_genrandbits(self):
261 # Verify cross-platform repeatability
262 self.gen.seed(1234567)
263 self.assertEqual(self.gen.getrandbits(100),
264 97904845777343510404718956115L)
265 # Verify ranges
266 for k in xrange(1, 1000):
267 self.assert_(0 <= self.gen.getrandbits(k) < 2**k)
268
269 # Verify all bits active
270 getbits = self.gen.getrandbits
271 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
272 cum = 0
273 for i in xrange(100):
274 cum |= getbits(span)
275 self.assertEqual(cum, 2**span-1)
276
277 def test_randbelow_logic(self, _log=log, int=int):
278 # check bitcount transition points: 2**i and 2**(i+1)-1
279 # show that: k = int(1.001 + _log(n, 2))
280 # is equal to or one greater than the number of bits in n
281 for i in xrange(1, 1000):
282 n = 1L << i # check an exact power of two
283 numbits = i+1
284 k = int(1.00001 + _log(n, 2))
285 self.assertEqual(k, numbits)
286 self.assert_(n == 2**(k-1))
287
288 n += n - 1 # check 1 below the next power of two
289 k = int(1.00001 + _log(n, 2))
290 self.assert_(k in [numbits, numbits+1])
291 self.assert_(2**k > n > 2**(k-2))
292
293 n -= n >> 15 # check a little farther below the next power of two
294 k = int(1.00001 + _log(n, 2))
295 self.assertEqual(k, numbits) # note the stronger assertion
296 self.assert_(2**k > n > 2**(k-1)) # note the stronger assertion
297
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000298_gammacoeff = (0.9999999999995183, 676.5203681218835, -1259.139216722289,
299 771.3234287757674, -176.6150291498386, 12.50734324009056,
300 -0.1385710331296526, 0.9934937113930748e-05, 0.1659470187408462e-06)
301
302def gamma(z, cof=_gammacoeff, g=7):
303 z -= 1.0
304 sum = cof[0]
305 for i in xrange(1,len(cof)):
306 sum += cof[i] / (z+i)
307 z += 0.5
308 return (z+g)**z / exp(z+g) * sqrt(2*pi) * sum
309
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000310class TestDistributions(unittest.TestCase):
311 def test_zeroinputs(self):
312 # Verify that distributions can handle a series of zero inputs'
313 g = random.Random()
314 x = [g.random() for i in xrange(50)] + [0.0]*5
315 g.random = x[:].pop; g.uniform(1,10)
316 g.random = x[:].pop; g.paretovariate(1.0)
317 g.random = x[:].pop; g.expovariate(1.0)
318 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
319 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
320 g.random = x[:].pop; g.gauss(0.0, 1.0)
321 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
322 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
323 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
324 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
325 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
326 g.random = x[:].pop; g.betavariate(3.0, 3.0)
327
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000328 def test_avg_std(self):
329 # Use integration to test distribution average and standard deviation.
330 # Only works for distributions which do not consume variates in pairs
331 g = random.Random()
332 N = 5000
333 x = [i/float(N) for i in xrange(1,N)]
334 for variate, args, mu, sigmasqrd in [
335 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
336 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
337 (g.paretovariate, (5.0,), 5.0/(5.0-1),
338 5.0/((5.0-1)**2*(5.0-2))),
339 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
340 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
341 g.random = x[:].pop
342 y = []
343 for i in xrange(len(x)):
344 try:
345 y.append(variate(*args))
346 except IndexError:
347 pass
348 s1 = s2 = 0
349 for e in y:
350 s1 += e
351 s2 += (e - mu) ** 2
352 N = len(y)
353 self.assertAlmostEqual(s1/N, mu, 2)
354 self.assertAlmostEqual(s2/(N-1), sigmasqrd, 2)
355
Raymond Hettinger40f62172002-12-29 23:03:38 +0000356class TestModule(unittest.TestCase):
357 def testMagicConstants(self):
358 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
359 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
360 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
361 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
362
363 def test__all__(self):
364 # tests validity but not completeness of the __all__ list
Raymond Hettingera690a992003-11-16 16:17:49 +0000365 self.failUnless(set(random.__all__) <= set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000366
Raymond Hettinger105b0842003-02-04 05:47:30 +0000367def test_main(verbose=None):
Raymond Hettinger27922ee2003-05-03 03:38:01 +0000368 testclasses = (WichmannHill_TestBasicOps,
Raymond Hettinger40f62172002-12-29 23:03:38 +0000369 MersenneTwister_TestBasicOps,
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000370 TestDistributions,
Raymond Hettinger27922ee2003-05-03 03:38:01 +0000371 TestModule)
372 test_support.run_unittest(*testclasses)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000373
Raymond Hettinger105b0842003-02-04 05:47:30 +0000374 # verify reference counting
375 import sys
376 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger320a1b02003-05-02 22:44:59 +0000377 counts = [None] * 5
378 for i in xrange(len(counts)):
Raymond Hettinger27922ee2003-05-03 03:38:01 +0000379 test_support.run_unittest(*testclasses)
Raymond Hettinger320a1b02003-05-02 22:44:59 +0000380 counts[i] = sys.gettotalrefcount()
Raymond Hettinger105b0842003-02-04 05:47:30 +0000381 print counts
382
Raymond Hettinger40f62172002-12-29 23:03:38 +0000383if __name__ == "__main__":
Raymond Hettinger105b0842003-02-04 05:47:30 +0000384 test_main(verbose=True)