blob: a9aec70f75d734a4dd2a47f2d94a577e75a275dc [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
Raymond Hettinger40f62172002-12-29 23:03:38 +00002
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
Georg Brandl1b37e872010-03-14 10:45:50 +00008from math import log, exp, pi, fsum, sin
Benjamin Petersonee8712c2008-05-20 21:35:26 +00009from test import 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"""
Guido van Rossum805365e2007-05-07 22:24:25 +000018 return [self.gen.random() for i in range(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):
Mark Dickinson95aeae02012-06-24 11:05:30 +010037 # Seed value with a negative hash.
38 class MySeed(object):
39 def __hash__(self):
40 return -1729
Guido van Rossume2a383d2007-01-15 16:59:06 +000041 for arg in [None, 0, 0, 1, 1, -1, -1, 10**20, -(10**20),
Mark Dickinson95aeae02012-06-24 11:05:30 +010042 3.14, 1+2j, 'a', tuple('abc'), MySeed()]:
Raymond Hettinger40f62172002-12-29 23:03:38 +000043 self.gen.seed(arg)
Guido van Rossum805365e2007-05-07 22:24:25 +000044 for arg in [list(range(3)), dict(one=1)]:
Raymond Hettinger40f62172002-12-29 23:03:38 +000045 self.assertRaises(TypeError, self.gen.seed, arg)
Raymond Hettingerf763a722010-09-07 00:38:15 +000046 self.assertRaises(TypeError, self.gen.seed, 1, 2, 3, 4)
Raymond Hettinger58335872004-07-09 14:26:18 +000047 self.assertRaises(TypeError, type(self.gen), [])
Raymond Hettinger40f62172002-12-29 23:03:38 +000048
Antoine Pitrou5e394332012-11-04 02:10:33 +010049 def test_shuffle(self):
50 shuffle = self.gen.shuffle
51 lst = []
52 shuffle(lst)
53 self.assertEqual(lst, [])
54 lst = [37]
55 shuffle(lst)
56 self.assertEqual(lst, [37])
57 seqs = [list(range(n)) for n in range(10)]
58 shuffled_seqs = [list(range(n)) for n in range(10)]
59 for shuffled_seq in shuffled_seqs:
60 shuffle(shuffled_seq)
61 for (seq, shuffled_seq) in zip(seqs, shuffled_seqs):
62 self.assertEqual(len(seq), len(shuffled_seq))
63 self.assertEqual(set(seq), set(shuffled_seq))
64
65 # The above tests all would pass if the shuffle was a
66 # no-op. The following non-deterministic test covers that. It
67 # asserts that the shuffled sequence of 1000 distinct elements
68 # must be different from the original one. Although there is
69 # mathematically a non-zero probability that this could
70 # actually happen in a genuinely random shuffle, it is
71 # completely negligible, given that the number of possible
72 # permutations of 1000 objects is 1000! (factorial of 1000),
73 # which is considerably larger than the number of atoms in the
74 # universe...
75 lst = list(range(1000))
76 shuffled_lst = list(range(1000))
77 shuffle(shuffled_lst)
78 self.assertTrue(lst != shuffled_lst)
79 shuffle(lst)
80 self.assertTrue(lst != shuffled_lst)
81
Raymond Hettingerdc4872e2010-09-07 10:06:56 +000082 def test_choice(self):
83 choice = self.gen.choice
84 with self.assertRaises(IndexError):
85 choice([])
86 self.assertEqual(choice([50]), 50)
87 self.assertIn(choice([25, 75]), [25, 75])
88
Raymond Hettinger40f62172002-12-29 23:03:38 +000089 def test_sample(self):
90 # For the entire allowable range of 0 <= k <= N, validate that
91 # the sample is of the correct length and contains only unique items
92 N = 100
Guido van Rossum805365e2007-05-07 22:24:25 +000093 population = range(N)
94 for k in range(N+1):
Raymond Hettinger40f62172002-12-29 23:03:38 +000095 s = self.gen.sample(population, k)
96 self.assertEqual(len(s), k)
Raymond Hettingera690a992003-11-16 16:17:49 +000097 uniq = set(s)
Raymond Hettinger40f62172002-12-29 23:03:38 +000098 self.assertEqual(len(uniq), k)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000099 self.assertTrue(uniq <= set(population))
Raymond Hettinger8ec78812003-01-04 05:55:11 +0000100 self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
Raymond Hettinger40f62172002-12-29 23:03:38 +0000101
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000102 def test_sample_distribution(self):
103 # For the entire allowable range of 0 <= k <= N, validate that
104 # sample generates all possible permutations
105 n = 5
106 pop = range(n)
107 trials = 10000 # large num prevents false negatives without slowing normal case
108 def factorial(n):
Guido van Rossum89da5d72006-08-22 00:21:25 +0000109 if n == 0:
110 return 1
111 return n * factorial(n - 1)
Guido van Rossum805365e2007-05-07 22:24:25 +0000112 for k in range(n):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000113 expected = factorial(n) // factorial(n-k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000114 perms = {}
Guido van Rossum805365e2007-05-07 22:24:25 +0000115 for i in range(trials):
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000116 perms[tuple(self.gen.sample(pop, k))] = None
117 if len(perms) == expected:
118 break
119 else:
120 self.fail()
121
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000122 def test_sample_inputs(self):
123 # SF bug #801342 -- population can be any iterable defining __len__()
Raymond Hettingera690a992003-11-16 16:17:49 +0000124 self.gen.sample(set(range(20)), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000125 self.gen.sample(range(20), 2)
Guido van Rossum805365e2007-05-07 22:24:25 +0000126 self.gen.sample(range(20), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000127 self.gen.sample(str('abcdefghijklmnopqrst'), 2)
128 self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
129
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000130 def test_sample_on_dicts(self):
Raymond Hettinger1acde192008-01-14 01:00:53 +0000131 self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000132
Raymond Hettinger40f62172002-12-29 23:03:38 +0000133 def test_gauss(self):
134 # Ensure that the seed() method initializes all the hidden state. In
135 # particular, through 2.2.1 it failed to reset a piece of state used
136 # by (and only by) the .gauss() method.
137
138 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
139 self.gen.seed(seed)
140 x1 = self.gen.random()
141 y1 = self.gen.gauss(0, 1)
142
143 self.gen.seed(seed)
144 x2 = self.gen.random()
145 y2 = self.gen.gauss(0, 1)
146
147 self.assertEqual(x1, x2)
148 self.assertEqual(y1, y2)
149
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000150 def test_pickling(self):
151 state = pickle.dumps(self.gen)
Guido van Rossum805365e2007-05-07 22:24:25 +0000152 origseq = [self.gen.random() for i in range(10)]
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000153 newgen = pickle.loads(state)
Guido van Rossum805365e2007-05-07 22:24:25 +0000154 restoredseq = [newgen.random() for i in range(10)]
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000155 self.assertEqual(origseq, restoredseq)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000156
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000157 def test_bug_1727780(self):
158 # verify that version-2-pickles can be loaded
159 # fine, whether they are created on 32-bit or 64-bit
160 # platforms, and that version-3-pickles load fine.
161 files = [("randv2_32.pck", 780),
162 ("randv2_64.pck", 866),
163 ("randv3.pck", 343)]
164 for file, value in files:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000165 f = open(support.findfile(file),"rb")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000166 r = pickle.load(f)
167 f.close()
Raymond Hettinger05156612010-09-07 04:44:52 +0000168 self.assertEqual(int(r.random()*1000), value)
169
170 def test_bug_9025(self):
171 # Had problem with an uneven distribution in int(n*random())
172 # Verify the fix by checking that distributions fall within expectations.
173 n = 100000
174 randrange = self.gen.randrange
175 k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n))
176 self.assertTrue(0.30 < k/n < .37, (k/n))
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000177
Raymond Hettinger23f12412004-09-13 22:23:21 +0000178class SystemRandom_TestBasicOps(TestBasicOps):
179 gen = random.SystemRandom()
Raymond Hettinger356a4592004-08-30 06:14:31 +0000180
181 def test_autoseed(self):
182 # Doesn't need to do anything except not fail
183 self.gen.seed()
184
185 def test_saverestore(self):
186 self.assertRaises(NotImplementedError, self.gen.getstate)
187 self.assertRaises(NotImplementedError, self.gen.setstate, None)
188
189 def test_seedargs(self):
190 # Doesn't need to do anything except not fail
191 self.gen.seed(100)
192
Raymond Hettinger356a4592004-08-30 06:14:31 +0000193 def test_gauss(self):
194 self.gen.gauss_next = None
195 self.gen.seed(100)
196 self.assertEqual(self.gen.gauss_next, None)
197
198 def test_pickling(self):
199 self.assertRaises(NotImplementedError, pickle.dumps, self.gen)
200
201 def test_53_bits_per_float(self):
202 # This should pass whenever a C double has 53 bit precision.
203 span = 2 ** 53
204 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000205 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000206 cum |= int(self.gen.random() * span)
207 self.assertEqual(cum, span-1)
208
209 def test_bigrand(self):
210 # The randrange routine should build-up the required number of bits
211 # in stages so that all bit positions are active.
212 span = 2 ** 500
213 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000214 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000215 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000216 self.assertTrue(0 <= r < span)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000217 cum |= r
218 self.assertEqual(cum, span-1)
219
220 def test_bigrand_ranges(self):
221 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
222 start = self.gen.randrange(2 ** i)
223 stop = self.gen.randrange(2 ** (i-2))
224 if stop <= start:
225 return
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000226 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000227
228 def test_rangelimits(self):
229 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
230 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000231 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000232
233 def test_genrandbits(self):
234 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000235 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000236 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000237
238 # Verify all bits active
239 getbits = self.gen.getrandbits
240 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
241 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000242 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000243 cum |= getbits(span)
244 self.assertEqual(cum, 2**span-1)
245
246 # Verify argument checking
247 self.assertRaises(TypeError, self.gen.getrandbits)
248 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
249 self.assertRaises(ValueError, self.gen.getrandbits, 0)
250 self.assertRaises(ValueError, self.gen.getrandbits, -1)
251 self.assertRaises(TypeError, self.gen.getrandbits, 10.1)
252
253 def test_randbelow_logic(self, _log=log, int=int):
254 # check bitcount transition points: 2**i and 2**(i+1)-1
255 # show that: k = int(1.001 + _log(n, 2))
256 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000257 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000258 n = 1 << i # check an exact power of two
Raymond Hettinger356a4592004-08-30 06:14:31 +0000259 numbits = i+1
260 k = int(1.00001 + _log(n, 2))
261 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000262 self.assertEqual(n, 2**(k-1))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000263
264 n += n - 1 # check 1 below the next power of two
265 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000266 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000267 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000268
269 n -= n >> 15 # check a little farther below the next power of two
270 k = int(1.00001 + _log(n, 2))
271 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000272 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger356a4592004-08-30 06:14:31 +0000273
274
Raymond Hettinger40f62172002-12-29 23:03:38 +0000275class MersenneTwister_TestBasicOps(TestBasicOps):
276 gen = random.Random()
277
Raymond Hettingerf763a722010-09-07 00:38:15 +0000278 def test_guaranteed_stable(self):
279 # These sequences are guaranteed to stay the same across versions of python
280 self.gen.seed(3456147, version=1)
281 self.assertEqual([self.gen.random().hex() for i in range(4)],
282 ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1',
283 '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000284 self.gen.seed("the quick brown fox", version=2)
285 self.assertEqual([self.gen.random().hex() for i in range(4)],
Raymond Hettinger3fcf0022010-12-08 01:13:53 +0000286 ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
287 '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000288
Raymond Hettinger58335872004-07-09 14:26:18 +0000289 def test_setstate_first_arg(self):
290 self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
291
292 def test_setstate_middle_arg(self):
293 # Wrong type, s/b tuple
294 self.assertRaises(TypeError, self.gen.setstate, (2, None, None))
295 # Wrong length, s/b 625
296 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None))
297 # Wrong type, s/b tuple of 625 ints
298 self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None))
299 # Last element s/b an int also
300 self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None))
301
Raymond Hettinger40f62172002-12-29 23:03:38 +0000302 def test_referenceImplementation(self):
303 # Compare the python implementation with results from the original
304 # code. Create 2000 53-bit precision random floats. Compare only
305 # the last ten entries to show that the independent implementations
306 # are tracking. Here is the main() function needed to create the
307 # list of expected random numbers:
308 # void main(void){
309 # int i;
310 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
311 # init_by_array(init, length);
312 # for (i=0; i<2000; i++) {
313 # printf("%.15f ", genrand_res53());
314 # if (i%5==4) printf("\n");
315 # }
316 # }
317 expected = [0.45839803073713259,
318 0.86057815201978782,
319 0.92848331726782152,
320 0.35932681119782461,
321 0.081823493762449573,
322 0.14332226470169329,
323 0.084297823823520024,
324 0.53814864671831453,
325 0.089215024911993401,
326 0.78486196105372907]
327
Guido van Rossume2a383d2007-01-15 16:59:06 +0000328 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000329 actual = self.randomlist(2000)[-10:]
330 for a, e in zip(actual, expected):
331 self.assertAlmostEqual(a,e,places=14)
332
333 def test_strong_reference_implementation(self):
334 # Like test_referenceImplementation, but checks for exact bit-level
335 # equality. This should pass on any box where C double contains
336 # at least 53 bits of precision (the underlying algorithm suffers
337 # no rounding errors -- all results are exact).
338 from math import ldexp
339
Guido van Rossume2a383d2007-01-15 16:59:06 +0000340 expected = [0x0eab3258d2231f,
341 0x1b89db315277a5,
342 0x1db622a5518016,
343 0x0b7f9af0d575bf,
344 0x029e4c4db82240,
345 0x04961892f5d673,
346 0x02b291598e4589,
347 0x11388382c15694,
348 0x02dad977c9e1fe,
349 0x191d96d4d334c6]
350 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000351 actual = self.randomlist(2000)[-10:]
352 for a, e in zip(actual, expected):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000353 self.assertEqual(int(ldexp(a, 53)), e)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000354
355 def test_long_seed(self):
356 # This is most interesting to run in debug mode, just to make sure
357 # nothing blows up. Under the covers, a dynamically resized array
358 # is allocated, consuming space proportional to the number of bits
359 # in the seed. Unfortunately, that's a quadratic-time algorithm,
360 # so don't make this horribly big.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000361 seed = (1 << (10000 * 8)) - 1 # about 10K bytes
Raymond Hettinger40f62172002-12-29 23:03:38 +0000362 self.gen.seed(seed)
363
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000364 def test_53_bits_per_float(self):
365 # This should pass whenever a C double has 53 bit precision.
366 span = 2 ** 53
367 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000368 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000369 cum |= int(self.gen.random() * span)
370 self.assertEqual(cum, span-1)
371
372 def test_bigrand(self):
373 # The randrange routine should build-up the required number of bits
374 # in stages so that all bit positions are active.
375 span = 2 ** 500
376 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000377 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000378 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000379 self.assertTrue(0 <= r < span)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000380 cum |= r
381 self.assertEqual(cum, span-1)
382
383 def test_bigrand_ranges(self):
384 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
385 start = self.gen.randrange(2 ** i)
386 stop = self.gen.randrange(2 ** (i-2))
387 if stop <= start:
388 return
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000389 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000390
391 def test_rangelimits(self):
392 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
Raymond Hettingera690a992003-11-16 16:17:49 +0000393 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000394 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000395
396 def test_genrandbits(self):
397 # Verify cross-platform repeatability
398 self.gen.seed(1234567)
399 self.assertEqual(self.gen.getrandbits(100),
Guido van Rossume2a383d2007-01-15 16:59:06 +0000400 97904845777343510404718956115)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000401 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000402 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000403 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000404
405 # Verify all bits active
406 getbits = self.gen.getrandbits
407 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
408 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000409 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000410 cum |= getbits(span)
411 self.assertEqual(cum, 2**span-1)
412
Raymond Hettinger58335872004-07-09 14:26:18 +0000413 # Verify argument checking
414 self.assertRaises(TypeError, self.gen.getrandbits)
415 self.assertRaises(TypeError, self.gen.getrandbits, 'a')
416 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
417 self.assertRaises(ValueError, self.gen.getrandbits, 0)
418 self.assertRaises(ValueError, self.gen.getrandbits, -1)
419
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000420 def test_randbelow_logic(self, _log=log, int=int):
421 # check bitcount transition points: 2**i and 2**(i+1)-1
422 # show that: k = int(1.001 + _log(n, 2))
423 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000424 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000425 n = 1 << i # check an exact power of two
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000426 numbits = i+1
427 k = int(1.00001 + _log(n, 2))
428 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000429 self.assertEqual(n, 2**(k-1))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000430
431 n += n - 1 # check 1 below the next power of two
432 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000433 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000434 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000435
436 n -= n >> 15 # check a little farther below the next power of two
437 k = int(1.00001 + _log(n, 2))
438 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000439 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000440
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000441 def test_randrange_bug_1590891(self):
442 start = 1000000000000
443 stop = -100000000000000000000
444 step = -200
445 x = self.gen.randrange(start, stop, step)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000446 self.assertTrue(stop < x <= start)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000447 self.assertEqual((x+stop)%step, 0)
448
Raymond Hettinger2d0c2562009-02-19 09:53:18 +0000449def gamma(z, sqrt2pi=(2.0*pi)**0.5):
450 # Reflection to right half of complex plane
451 if z < 0.5:
452 return pi / sin(pi*z) / gamma(1.0-z)
453 # Lanczos approximation with g=7
454 az = z + (7.0 - 0.5)
455 return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
456 0.9999999999995183,
457 676.5203681218835 / z,
458 -1259.139216722289 / (z+1.0),
459 771.3234287757674 / (z+2.0),
460 -176.6150291498386 / (z+3.0),
461 12.50734324009056 / (z+4.0),
462 -0.1385710331296526 / (z+5.0),
463 0.9934937113930748e-05 / (z+6.0),
464 0.1659470187408462e-06 / (z+7.0),
465 ])
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000466
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000467class TestDistributions(unittest.TestCase):
468 def test_zeroinputs(self):
469 # Verify that distributions can handle a series of zero inputs'
470 g = random.Random()
Guido van Rossum805365e2007-05-07 22:24:25 +0000471 x = [g.random() for i in range(50)] + [0.0]*5
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000472 g.random = x[:].pop; g.uniform(1,10)
473 g.random = x[:].pop; g.paretovariate(1.0)
474 g.random = x[:].pop; g.expovariate(1.0)
475 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
476 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
477 g.random = x[:].pop; g.gauss(0.0, 1.0)
478 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
479 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
480 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
481 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
482 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
483 g.random = x[:].pop; g.betavariate(3.0, 3.0)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000484 g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000485
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000486 def test_avg_std(self):
487 # Use integration to test distribution average and standard deviation.
488 # Only works for distributions which do not consume variates in pairs
489 g = random.Random()
490 N = 5000
Guido van Rossum805365e2007-05-07 22:24:25 +0000491 x = [i/float(N) for i in range(1,N)]
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000492 for variate, args, mu, sigmasqrd in [
493 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
Christian Heimesfe337bf2008-03-23 21:54:12 +0000494 (g.triangular, (0.0, 1.0, 1.0/3.0), 4.0/9.0, 7.0/9.0/18.0),
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000495 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
496 (g.paretovariate, (5.0,), 5.0/(5.0-1),
497 5.0/((5.0-1)**2*(5.0-2))),
498 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
499 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
500 g.random = x[:].pop
501 y = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000502 for i in range(len(x)):
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000503 try:
504 y.append(variate(*args))
505 except IndexError:
506 pass
507 s1 = s2 = 0
508 for e in y:
509 s1 += e
510 s2 += (e - mu) ** 2
511 N = len(y)
Jeffrey Yasskin48952d32007-09-07 15:45:05 +0000512 self.assertAlmostEqual(s1/N, mu, places=2)
513 self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2)
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000514
Raymond Hettinger40f62172002-12-29 23:03:38 +0000515class TestModule(unittest.TestCase):
516 def testMagicConstants(self):
517 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
518 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
519 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
520 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
521
522 def test__all__(self):
523 # tests validity but not completeness of the __all__ list
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000524 self.assertTrue(set(random.__all__) <= set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000525
Thomas Woutersb2137042007-02-01 18:02:27 +0000526 def test_random_subclass_with_kwargs(self):
527 # SF bug #1486663 -- this used to erroneously raise a TypeError
528 class Subclass(random.Random):
529 def __init__(self, newarg=None):
530 random.Random.__init__(self)
531 Subclass(newarg=1)
532
533
Raymond Hettinger105b0842003-02-04 05:47:30 +0000534def test_main(verbose=None):
Raymond Hettinger28de64f2008-01-13 23:40:30 +0000535 testclasses = [MersenneTwister_TestBasicOps,
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000536 TestDistributions,
Raymond Hettingerb8717632004-09-04 20:13:29 +0000537 TestModule]
538
Raymond Hettingerc1c43ca2004-09-05 00:00:42 +0000539 try:
Raymond Hettinger23f12412004-09-13 22:23:21 +0000540 random.SystemRandom().random()
Raymond Hettingerc1c43ca2004-09-05 00:00:42 +0000541 except NotImplementedError:
542 pass
543 else:
Raymond Hettinger23f12412004-09-13 22:23:21 +0000544 testclasses.append(SystemRandom_TestBasicOps)
Raymond Hettingerb8717632004-09-04 20:13:29 +0000545
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000546 support.run_unittest(*testclasses)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000547
Raymond Hettinger105b0842003-02-04 05:47:30 +0000548 # verify reference counting
549 import sys
550 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger320a1b02003-05-02 22:44:59 +0000551 counts = [None] * 5
Guido van Rossum805365e2007-05-07 22:24:25 +0000552 for i in range(len(counts)):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000553 support.run_unittest(*testclasses)
Raymond Hettinger320a1b02003-05-02 22:44:59 +0000554 counts[i] = sys.gettotalrefcount()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000555 print(counts)
Raymond Hettinger105b0842003-02-04 05:47:30 +0000556
Raymond Hettinger40f62172002-12-29 23:03:38 +0000557if __name__ == "__main__":
Raymond Hettinger105b0842003-02-04 05:47:30 +0000558 test_main(verbose=True)