blob: 103d462c6411850aa6fb09adbd478af8780a1f73 [file] [log] [blame]
Raymond Hettinger40f62172002-12-29 23:03:38 +00001import unittest
R David Murraye3e1c172013-04-02 12:47:23 -04002import unittest.mock
Tim Peters46c04e12002-05-05 20:40:00 +00003import random
Raymond Hettinger40f62172002-12-29 23:03:38 +00004import time
Raymond Hettinger5f078ff2003-06-24 20:29:04 +00005import pickle
Raymond Hettinger2f726e92003-10-05 09:09:15 +00006import warnings
R David Murraye3e1c172013-04-02 12:47:23 -04007from functools import partial
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
Ezio Melotti3e4a98b2013-04-19 05:45:27 +030011class TestBasicOps:
Raymond Hettinger40f62172002-12-29 23:03:38 +000012 # 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
R David Murraye3e1c172013-04-02 12:47:23 -040049 @unittest.mock.patch('random._urandom') # os.urandom
50 def test_seed_when_randomness_source_not_found(self, urandom_mock):
51 # Random.seed() uses time.time() when an operating system specific
52 # randomness source is not found. To test this on machines were it
53 # exists, run the above test, test_seedargs(), again after mocking
54 # os.urandom() so that it raises the exception expected when the
55 # randomness source is not available.
56 urandom_mock.side_effect = NotImplementedError
57 self.test_seedargs()
58
Antoine Pitrou5e394332012-11-04 02:10:33 +010059 def test_shuffle(self):
60 shuffle = self.gen.shuffle
61 lst = []
62 shuffle(lst)
63 self.assertEqual(lst, [])
64 lst = [37]
65 shuffle(lst)
66 self.assertEqual(lst, [37])
67 seqs = [list(range(n)) for n in range(10)]
68 shuffled_seqs = [list(range(n)) for n in range(10)]
69 for shuffled_seq in shuffled_seqs:
70 shuffle(shuffled_seq)
71 for (seq, shuffled_seq) in zip(seqs, shuffled_seqs):
72 self.assertEqual(len(seq), len(shuffled_seq))
73 self.assertEqual(set(seq), set(shuffled_seq))
Antoine Pitrou5e394332012-11-04 02:10:33 +010074 # The above tests all would pass if the shuffle was a
75 # no-op. The following non-deterministic test covers that. It
76 # asserts that the shuffled sequence of 1000 distinct elements
77 # must be different from the original one. Although there is
78 # mathematically a non-zero probability that this could
79 # actually happen in a genuinely random shuffle, it is
80 # completely negligible, given that the number of possible
81 # permutations of 1000 objects is 1000! (factorial of 1000),
82 # which is considerably larger than the number of atoms in the
83 # universe...
84 lst = list(range(1000))
85 shuffled_lst = list(range(1000))
86 shuffle(shuffled_lst)
87 self.assertTrue(lst != shuffled_lst)
88 shuffle(lst)
89 self.assertTrue(lst != shuffled_lst)
90
Raymond Hettingerdc4872e2010-09-07 10:06:56 +000091 def test_choice(self):
92 choice = self.gen.choice
93 with self.assertRaises(IndexError):
94 choice([])
95 self.assertEqual(choice([50]), 50)
96 self.assertIn(choice([25, 75]), [25, 75])
97
Raymond Hettinger40f62172002-12-29 23:03:38 +000098 def test_sample(self):
99 # For the entire allowable range of 0 <= k <= N, validate that
100 # the sample is of the correct length and contains only unique items
101 N = 100
Guido van Rossum805365e2007-05-07 22:24:25 +0000102 population = range(N)
103 for k in range(N+1):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000104 s = self.gen.sample(population, k)
105 self.assertEqual(len(s), k)
Raymond Hettingera690a992003-11-16 16:17:49 +0000106 uniq = set(s)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000107 self.assertEqual(len(uniq), k)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000108 self.assertTrue(uniq <= set(population))
Raymond Hettinger8ec78812003-01-04 05:55:11 +0000109 self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
R David Murraye3e1c172013-04-02 12:47:23 -0400110 # Exception raised if size of sample exceeds that of population
111 self.assertRaises(ValueError, self.gen.sample, population, N+1)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000112
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000113 def test_sample_distribution(self):
114 # For the entire allowable range of 0 <= k <= N, validate that
115 # sample generates all possible permutations
116 n = 5
117 pop = range(n)
118 trials = 10000 # large num prevents false negatives without slowing normal case
119 def factorial(n):
Guido van Rossum89da5d72006-08-22 00:21:25 +0000120 if n == 0:
121 return 1
122 return n * factorial(n - 1)
Guido van Rossum805365e2007-05-07 22:24:25 +0000123 for k in range(n):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000124 expected = factorial(n) // factorial(n-k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000125 perms = {}
Guido van Rossum805365e2007-05-07 22:24:25 +0000126 for i in range(trials):
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000127 perms[tuple(self.gen.sample(pop, k))] = None
128 if len(perms) == expected:
129 break
130 else:
131 self.fail()
132
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000133 def test_sample_inputs(self):
134 # SF bug #801342 -- population can be any iterable defining __len__()
Raymond Hettingera690a992003-11-16 16:17:49 +0000135 self.gen.sample(set(range(20)), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000136 self.gen.sample(range(20), 2)
Guido van Rossum805365e2007-05-07 22:24:25 +0000137 self.gen.sample(range(20), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000138 self.gen.sample(str('abcdefghijklmnopqrst'), 2)
139 self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
140
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000141 def test_sample_on_dicts(self):
Raymond Hettinger1acde192008-01-14 01:00:53 +0000142 self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000143
Raymond Hettinger40f62172002-12-29 23:03:38 +0000144 def test_gauss(self):
145 # Ensure that the seed() method initializes all the hidden state. In
146 # particular, through 2.2.1 it failed to reset a piece of state used
147 # by (and only by) the .gauss() method.
148
149 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
150 self.gen.seed(seed)
151 x1 = self.gen.random()
152 y1 = self.gen.gauss(0, 1)
153
154 self.gen.seed(seed)
155 x2 = self.gen.random()
156 y2 = self.gen.gauss(0, 1)
157
158 self.assertEqual(x1, x2)
159 self.assertEqual(y1, y2)
160
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000161 def test_pickling(self):
162 state = pickle.dumps(self.gen)
Guido van Rossum805365e2007-05-07 22:24:25 +0000163 origseq = [self.gen.random() for i in range(10)]
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000164 newgen = pickle.loads(state)
Guido van Rossum805365e2007-05-07 22:24:25 +0000165 restoredseq = [newgen.random() for i in range(10)]
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000166 self.assertEqual(origseq, restoredseq)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000167
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000168 def test_bug_1727780(self):
169 # verify that version-2-pickles can be loaded
170 # fine, whether they are created on 32-bit or 64-bit
171 # platforms, and that version-3-pickles load fine.
172 files = [("randv2_32.pck", 780),
173 ("randv2_64.pck", 866),
174 ("randv3.pck", 343)]
175 for file, value in files:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000176 f = open(support.findfile(file),"rb")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000177 r = pickle.load(f)
178 f.close()
Raymond Hettinger05156612010-09-07 04:44:52 +0000179 self.assertEqual(int(r.random()*1000), value)
180
181 def test_bug_9025(self):
182 # Had problem with an uneven distribution in int(n*random())
183 # Verify the fix by checking that distributions fall within expectations.
184 n = 100000
185 randrange = self.gen.randrange
186 k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n))
187 self.assertTrue(0.30 < k/n < .37, (k/n))
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000188
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300189try:
190 random.SystemRandom().random()
191except NotImplementedError:
192 SystemRandom_available = False
193else:
194 SystemRandom_available = True
195
196@unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available")
197class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000198 gen = random.SystemRandom()
Raymond Hettinger356a4592004-08-30 06:14:31 +0000199
200 def test_autoseed(self):
201 # Doesn't need to do anything except not fail
202 self.gen.seed()
203
204 def test_saverestore(self):
205 self.assertRaises(NotImplementedError, self.gen.getstate)
206 self.assertRaises(NotImplementedError, self.gen.setstate, None)
207
208 def test_seedargs(self):
209 # Doesn't need to do anything except not fail
210 self.gen.seed(100)
211
Raymond Hettinger356a4592004-08-30 06:14:31 +0000212 def test_gauss(self):
213 self.gen.gauss_next = None
214 self.gen.seed(100)
215 self.assertEqual(self.gen.gauss_next, None)
216
217 def test_pickling(self):
218 self.assertRaises(NotImplementedError, pickle.dumps, self.gen)
219
220 def test_53_bits_per_float(self):
221 # This should pass whenever a C double has 53 bit precision.
222 span = 2 ** 53
223 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000224 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000225 cum |= int(self.gen.random() * span)
226 self.assertEqual(cum, span-1)
227
228 def test_bigrand(self):
229 # The randrange routine should build-up the required number of bits
230 # in stages so that all bit positions are active.
231 span = 2 ** 500
232 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000233 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000234 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000235 self.assertTrue(0 <= r < span)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000236 cum |= r
237 self.assertEqual(cum, span-1)
238
239 def test_bigrand_ranges(self):
240 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600241 start = self.gen.randrange(2 ** (i-2))
242 stop = self.gen.randrange(2 ** i)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000243 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600244 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000245 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000246
247 def test_rangelimits(self):
248 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
249 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000250 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000251
R David Murraye3e1c172013-04-02 12:47:23 -0400252 def test_randrange_nonunit_step(self):
253 rint = self.gen.randrange(0, 10, 2)
254 self.assertIn(rint, (0, 2, 4, 6, 8))
255 rint = self.gen.randrange(0, 2, 2)
256 self.assertEqual(rint, 0)
257
258 def test_randrange_errors(self):
259 raises = partial(self.assertRaises, ValueError, self.gen.randrange)
260 # Empty range
261 raises(3, 3)
262 raises(-721)
263 raises(0, 100, -12)
264 # Non-integer start/stop
265 raises(3.14159)
266 raises(0, 2.71828)
267 # Zero and non-integer step
268 raises(0, 42, 0)
269 raises(0, 42, 3.14159)
270
Raymond Hettinger356a4592004-08-30 06:14:31 +0000271 def test_genrandbits(self):
272 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000273 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000274 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000275
276 # Verify all bits active
277 getbits = self.gen.getrandbits
278 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
279 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000280 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000281 cum |= getbits(span)
282 self.assertEqual(cum, 2**span-1)
283
284 # Verify argument checking
285 self.assertRaises(TypeError, self.gen.getrandbits)
286 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
287 self.assertRaises(ValueError, self.gen.getrandbits, 0)
288 self.assertRaises(ValueError, self.gen.getrandbits, -1)
289 self.assertRaises(TypeError, self.gen.getrandbits, 10.1)
290
291 def test_randbelow_logic(self, _log=log, int=int):
292 # check bitcount transition points: 2**i and 2**(i+1)-1
293 # show that: k = int(1.001 + _log(n, 2))
294 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000295 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000296 n = 1 << i # check an exact power of two
Raymond Hettinger356a4592004-08-30 06:14:31 +0000297 numbits = i+1
298 k = int(1.00001 + _log(n, 2))
299 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000300 self.assertEqual(n, 2**(k-1))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000301
302 n += n - 1 # check 1 below the next power of two
303 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000304 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000305 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000306
307 n -= n >> 15 # check a little farther below the next power of two
308 k = int(1.00001 + _log(n, 2))
309 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000310 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger356a4592004-08-30 06:14:31 +0000311
312
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300313class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000314 gen = random.Random()
315
Raymond Hettingerf763a722010-09-07 00:38:15 +0000316 def test_guaranteed_stable(self):
317 # These sequences are guaranteed to stay the same across versions of python
318 self.gen.seed(3456147, version=1)
319 self.assertEqual([self.gen.random().hex() for i in range(4)],
320 ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1',
321 '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000322 self.gen.seed("the quick brown fox", version=2)
323 self.assertEqual([self.gen.random().hex() for i in range(4)],
Raymond Hettinger3fcf0022010-12-08 01:13:53 +0000324 ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
325 '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000326
Raymond Hettinger58335872004-07-09 14:26:18 +0000327 def test_setstate_first_arg(self):
328 self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
329
330 def test_setstate_middle_arg(self):
331 # Wrong type, s/b tuple
332 self.assertRaises(TypeError, self.gen.setstate, (2, None, None))
333 # Wrong length, s/b 625
334 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None))
335 # Wrong type, s/b tuple of 625 ints
336 self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None))
337 # Last element s/b an int also
338 self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None))
339
R David Murraye3e1c172013-04-02 12:47:23 -0400340 # Little trick to make "tuple(x % (2**32) for x in internalstate)"
341 # raise ValueError. I cannot think of a simple way to achieve this, so
342 # I am opting for using a generator as the middle argument of setstate
343 # which attempts to cast a NaN to integer.
344 state_values = self.gen.getstate()[1]
345 state_values = list(state_values)
346 state_values[-1] = float('nan')
347 state = (int(x) for x in state_values)
348 self.assertRaises(TypeError, self.gen.setstate, (2, state, None))
349
Raymond Hettinger40f62172002-12-29 23:03:38 +0000350 def test_referenceImplementation(self):
351 # Compare the python implementation with results from the original
352 # code. Create 2000 53-bit precision random floats. Compare only
353 # the last ten entries to show that the independent implementations
354 # are tracking. Here is the main() function needed to create the
355 # list of expected random numbers:
356 # void main(void){
357 # int i;
358 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
359 # init_by_array(init, length);
360 # for (i=0; i<2000; i++) {
361 # printf("%.15f ", genrand_res53());
362 # if (i%5==4) printf("\n");
363 # }
364 # }
365 expected = [0.45839803073713259,
366 0.86057815201978782,
367 0.92848331726782152,
368 0.35932681119782461,
369 0.081823493762449573,
370 0.14332226470169329,
371 0.084297823823520024,
372 0.53814864671831453,
373 0.089215024911993401,
374 0.78486196105372907]
375
Guido van Rossume2a383d2007-01-15 16:59:06 +0000376 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000377 actual = self.randomlist(2000)[-10:]
378 for a, e in zip(actual, expected):
379 self.assertAlmostEqual(a,e,places=14)
380
381 def test_strong_reference_implementation(self):
382 # Like test_referenceImplementation, but checks for exact bit-level
383 # equality. This should pass on any box where C double contains
384 # at least 53 bits of precision (the underlying algorithm suffers
385 # no rounding errors -- all results are exact).
386 from math import ldexp
387
Guido van Rossume2a383d2007-01-15 16:59:06 +0000388 expected = [0x0eab3258d2231f,
389 0x1b89db315277a5,
390 0x1db622a5518016,
391 0x0b7f9af0d575bf,
392 0x029e4c4db82240,
393 0x04961892f5d673,
394 0x02b291598e4589,
395 0x11388382c15694,
396 0x02dad977c9e1fe,
397 0x191d96d4d334c6]
398 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000399 actual = self.randomlist(2000)[-10:]
400 for a, e in zip(actual, expected):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000401 self.assertEqual(int(ldexp(a, 53)), e)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000402
403 def test_long_seed(self):
404 # This is most interesting to run in debug mode, just to make sure
405 # nothing blows up. Under the covers, a dynamically resized array
406 # is allocated, consuming space proportional to the number of bits
407 # in the seed. Unfortunately, that's a quadratic-time algorithm,
408 # so don't make this horribly big.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000409 seed = (1 << (10000 * 8)) - 1 # about 10K bytes
Raymond Hettinger40f62172002-12-29 23:03:38 +0000410 self.gen.seed(seed)
411
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000412 def test_53_bits_per_float(self):
413 # This should pass whenever a C double has 53 bit precision.
414 span = 2 ** 53
415 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000416 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000417 cum |= int(self.gen.random() * span)
418 self.assertEqual(cum, span-1)
419
420 def test_bigrand(self):
421 # The randrange routine should build-up the required number of bits
422 # in stages so that all bit positions are active.
423 span = 2 ** 500
424 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000425 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000426 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000427 self.assertTrue(0 <= r < span)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000428 cum |= r
429 self.assertEqual(cum, span-1)
430
431 def test_bigrand_ranges(self):
432 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600433 start = self.gen.randrange(2 ** (i-2))
434 stop = self.gen.randrange(2 ** i)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000435 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600436 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000437 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000438
439 def test_rangelimits(self):
440 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
Raymond Hettingera690a992003-11-16 16:17:49 +0000441 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000442 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000443
444 def test_genrandbits(self):
445 # Verify cross-platform repeatability
446 self.gen.seed(1234567)
447 self.assertEqual(self.gen.getrandbits(100),
Guido van Rossume2a383d2007-01-15 16:59:06 +0000448 97904845777343510404718956115)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000449 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000450 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000451 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000452
453 # Verify all bits active
454 getbits = self.gen.getrandbits
455 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
456 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000457 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000458 cum |= getbits(span)
459 self.assertEqual(cum, 2**span-1)
460
Raymond Hettinger58335872004-07-09 14:26:18 +0000461 # Verify argument checking
462 self.assertRaises(TypeError, self.gen.getrandbits)
463 self.assertRaises(TypeError, self.gen.getrandbits, 'a')
464 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
465 self.assertRaises(ValueError, self.gen.getrandbits, 0)
466 self.assertRaises(ValueError, self.gen.getrandbits, -1)
467
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000468 def test_randbelow_logic(self, _log=log, int=int):
469 # check bitcount transition points: 2**i and 2**(i+1)-1
470 # show that: k = int(1.001 + _log(n, 2))
471 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000472 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000473 n = 1 << i # check an exact power of two
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000474 numbits = i+1
475 k = int(1.00001 + _log(n, 2))
476 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000477 self.assertEqual(n, 2**(k-1))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000478
479 n += n - 1 # check 1 below the next power of two
480 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000481 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000482 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000483
484 n -= n >> 15 # check a little farther below the next power of two
485 k = int(1.00001 + _log(n, 2))
486 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000487 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000488
R David Murraye3e1c172013-04-02 12:47:23 -0400489 @unittest.mock.patch('random.Random.random')
490 def test_randbelow_overriden_random(self, random_mock):
491 # Random._randbelow() can only use random() when the built-in one
492 # has been overridden but no new getrandbits() method was supplied.
493 random_mock.side_effect = random.SystemRandom().random
494 maxsize = 1<<random.BPF
495 with warnings.catch_warnings():
496 warnings.simplefilter("ignore", UserWarning)
497 # Population range too large (n >= maxsize)
498 self.gen._randbelow(maxsize+1, maxsize = maxsize)
499 self.gen._randbelow(5640, maxsize = maxsize)
500
501 # This might be going too far to test a single line, but because of our
502 # noble aim of achieving 100% test coverage we need to write a case in
503 # which the following line in Random._randbelow() gets executed:
504 #
505 # rem = maxsize % n
506 # limit = (maxsize - rem) / maxsize
507 # r = random()
508 # while r >= limit:
509 # r = random() # <== *This line* <==<
510 #
511 # Therefore, to guarantee that the while loop is executed at least
512 # once, we need to mock random() so that it returns a number greater
513 # than 'limit' the first time it gets called.
514
515 n = 42
516 epsilon = 0.01
517 limit = (maxsize - (maxsize % n)) / maxsize
518 random_mock.side_effect = [limit + epsilon, limit - epsilon]
519 self.gen._randbelow(n, maxsize = maxsize)
520
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000521 def test_randrange_bug_1590891(self):
522 start = 1000000000000
523 stop = -100000000000000000000
524 step = -200
525 x = self.gen.randrange(start, stop, step)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000526 self.assertTrue(stop < x <= start)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000527 self.assertEqual((x+stop)%step, 0)
528
Raymond Hettinger2d0c2562009-02-19 09:53:18 +0000529def gamma(z, sqrt2pi=(2.0*pi)**0.5):
530 # Reflection to right half of complex plane
531 if z < 0.5:
532 return pi / sin(pi*z) / gamma(1.0-z)
533 # Lanczos approximation with g=7
534 az = z + (7.0 - 0.5)
535 return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
536 0.9999999999995183,
537 676.5203681218835 / z,
538 -1259.139216722289 / (z+1.0),
539 771.3234287757674 / (z+2.0),
540 -176.6150291498386 / (z+3.0),
541 12.50734324009056 / (z+4.0),
542 -0.1385710331296526 / (z+5.0),
543 0.9934937113930748e-05 / (z+6.0),
544 0.1659470187408462e-06 / (z+7.0),
545 ])
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000546
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000547class TestDistributions(unittest.TestCase):
548 def test_zeroinputs(self):
549 # Verify that distributions can handle a series of zero inputs'
550 g = random.Random()
Guido van Rossum805365e2007-05-07 22:24:25 +0000551 x = [g.random() for i in range(50)] + [0.0]*5
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000552 g.random = x[:].pop; g.uniform(1,10)
553 g.random = x[:].pop; g.paretovariate(1.0)
554 g.random = x[:].pop; g.expovariate(1.0)
555 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200556 g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000557 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
558 g.random = x[:].pop; g.gauss(0.0, 1.0)
559 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
560 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
561 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
562 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
563 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
564 g.random = x[:].pop; g.betavariate(3.0, 3.0)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000565 g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000566
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000567 def test_avg_std(self):
568 # Use integration to test distribution average and standard deviation.
569 # Only works for distributions which do not consume variates in pairs
570 g = random.Random()
571 N = 5000
Guido van Rossum805365e2007-05-07 22:24:25 +0000572 x = [i/float(N) for i in range(1,N)]
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000573 for variate, args, mu, sigmasqrd in [
574 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
Christian Heimesfe337bf2008-03-23 21:54:12 +0000575 (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 +0000576 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200577 (g.vonmisesvariate, (1.23, 0), pi, pi**2/3),
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000578 (g.paretovariate, (5.0,), 5.0/(5.0-1),
579 5.0/((5.0-1)**2*(5.0-2))),
580 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
581 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
582 g.random = x[:].pop
583 y = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000584 for i in range(len(x)):
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000585 try:
586 y.append(variate(*args))
587 except IndexError:
588 pass
589 s1 = s2 = 0
590 for e in y:
591 s1 += e
592 s2 += (e - mu) ** 2
593 N = len(y)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200594 self.assertAlmostEqual(s1/N, mu, places=2,
595 msg='%s%r' % (variate.__name__, args))
596 self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
597 msg='%s%r' % (variate.__name__, args))
598
599 def test_constant(self):
600 g = random.Random()
601 N = 100
602 for variate, args, expected in [
603 (g.uniform, (10.0, 10.0), 10.0),
604 (g.triangular, (10.0, 10.0), 10.0),
Raymond Hettinger978c6ab2014-05-25 17:25:27 -0700605 (g.triangular, (10.0, 10.0, 10.0), 10.0),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200606 (g.expovariate, (float('inf'),), 0.0),
607 (g.vonmisesvariate, (3.0, float('inf')), 3.0),
608 (g.gauss, (10.0, 0.0), 10.0),
609 (g.lognormvariate, (0.0, 0.0), 1.0),
610 (g.lognormvariate, (-float('inf'), 0.0), 0.0),
611 (g.normalvariate, (10.0, 0.0), 10.0),
612 (g.paretovariate, (float('inf'),), 1.0),
613 (g.weibullvariate, (10.0, float('inf')), 10.0),
614 (g.weibullvariate, (0.0, 10.0), 0.0),
615 ]:
616 for i in range(N):
617 self.assertEqual(variate(*args), expected)
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000618
Mark Dickinsonbe5f9192013-02-10 14:16:10 +0000619 def test_von_mises_range(self):
620 # Issue 17149: von mises variates were not consistently in the
621 # range [0, 2*PI].
622 g = random.Random()
623 N = 100
624 for mu in 0.0, 0.1, 3.1, 6.2:
625 for kappa in 0.0, 2.3, 500.0:
626 for _ in range(N):
627 sample = g.vonmisesvariate(mu, kappa)
628 self.assertTrue(
629 0 <= sample <= random.TWOPI,
630 msg=("vonmisesvariate({}, {}) produced a result {} out"
631 " of range [0, 2*pi]").format(mu, kappa, sample))
632
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200633 def test_von_mises_large_kappa(self):
634 # Issue #17141: vonmisesvariate() was hang for large kappas
635 random.vonmisesvariate(0, 1e15)
636 random.vonmisesvariate(0, 1e100)
637
R David Murraye3e1c172013-04-02 12:47:23 -0400638 def test_gammavariate_errors(self):
639 # Both alpha and beta must be > 0.0
640 self.assertRaises(ValueError, random.gammavariate, -1, 3)
641 self.assertRaises(ValueError, random.gammavariate, 0, 2)
642 self.assertRaises(ValueError, random.gammavariate, 2, 0)
643 self.assertRaises(ValueError, random.gammavariate, 1, -3)
644
645 @unittest.mock.patch('random.Random.random')
646 def test_gammavariate_full_code_coverage(self, random_mock):
647 # There are three different possibilities in the current implementation
648 # of random.gammavariate(), depending on the value of 'alpha'. What we
649 # are going to do here is to fix the values returned by random() to
650 # generate test cases that provide 100% line coverage of the method.
651
652 # #1: alpha > 1.0: we want the first random number to be outside the
653 # [1e-7, .9999999] range, so that the continue statement executes
654 # once. The values of u1 and u2 will be 0.5 and 0.3, respectively.
655 random_mock.side_effect = [1e-8, 0.5, 0.3]
656 returned_value = random.gammavariate(1.1, 2.3)
657 self.assertAlmostEqual(returned_value, 2.53)
658
659 # #2: alpha == 1: first random number less than 1e-7 to that the body
660 # of the while loop executes once. Then random.random() returns 0.45,
661 # which causes while to stop looping and the algorithm to terminate.
662 random_mock.side_effect = [1e-8, 0.45]
663 returned_value = random.gammavariate(1.0, 3.14)
664 self.assertAlmostEqual(returned_value, 2.507314166123803)
665
666 # #3: 0 < alpha < 1. This is the most complex region of code to cover,
667 # as there are multiple if-else statements. Let's take a look at the
668 # source code, and determine the values that we need accordingly:
669 #
670 # while 1:
671 # u = random()
672 # b = (_e + alpha)/_e
673 # p = b*u
674 # if p <= 1.0: # <=== (A)
675 # x = p ** (1.0/alpha)
676 # else: # <=== (B)
677 # x = -_log((b-p)/alpha)
678 # u1 = random()
679 # if p > 1.0: # <=== (C)
680 # if u1 <= x ** (alpha - 1.0): # <=== (D)
681 # break
682 # elif u1 <= _exp(-x): # <=== (E)
683 # break
684 # return x * beta
685 #
686 # First, we want (A) to be True. For that we need that:
687 # b*random() <= 1.0
688 # r1 = random() <= 1.0 / b
689 #
690 # We now get to the second if-else branch, and here, since p <= 1.0,
691 # (C) is False and we take the elif branch, (E). For it to be True,
692 # so that the break is executed, we need that:
693 # r2 = random() <= _exp(-x)
694 # r2 <= _exp(-(p ** (1.0/alpha)))
695 # r2 <= _exp(-((b*r1) ** (1.0/alpha)))
696
697 _e = random._e
698 _exp = random._exp
699 _log = random._log
700 alpha = 0.35
701 beta = 1.45
702 b = (_e + alpha)/_e
703 epsilon = 0.01
704
705 r1 = 0.8859296441566 # 1.0 / b
706 r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha)))
707
708 # These four "random" values result in the following trace:
709 # (A) True, (E) False --> [next iteration of while]
710 # (A) True, (E) True --> [while loop breaks]
711 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
712 returned_value = random.gammavariate(alpha, beta)
713 self.assertAlmostEqual(returned_value, 1.4499999999997544)
714
715 # Let's now make (A) be False. If this is the case, when we get to the
716 # second if-else 'p' is greater than 1, so (C) evaluates to True. We
717 # now encounter a second if statement, (D), which in order to execute
718 # must satisfy the following condition:
719 # r2 <= x ** (alpha - 1.0)
720 # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0)
721 # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0)
722 r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False
723 r2 = 0.9445400408898141
724
725 # And these four values result in the following trace:
726 # (B) and (C) True, (D) False --> [next iteration of while]
727 # (B) and (C) True, (D) True [while loop breaks]
728 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
729 returned_value = random.gammavariate(alpha, beta)
730 self.assertAlmostEqual(returned_value, 1.5830349561760781)
731
732 @unittest.mock.patch('random.Random.gammavariate')
733 def test_betavariate_return_zero(self, gammavariate_mock):
734 # betavariate() returns zero when the Gamma distribution
735 # that it uses internally returns this same value.
736 gammavariate_mock.return_value = 0.0
737 self.assertEqual(0.0, random.betavariate(2.71828, 3.14159))
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200738
Raymond Hettinger40f62172002-12-29 23:03:38 +0000739class TestModule(unittest.TestCase):
740 def testMagicConstants(self):
741 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
742 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
743 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
744 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
745
746 def test__all__(self):
747 # tests validity but not completeness of the __all__ list
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000748 self.assertTrue(set(random.__all__) <= set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000749
Thomas Woutersb2137042007-02-01 18:02:27 +0000750 def test_random_subclass_with_kwargs(self):
751 # SF bug #1486663 -- this used to erroneously raise a TypeError
752 class Subclass(random.Random):
753 def __init__(self, newarg=None):
754 random.Random.__init__(self)
755 Subclass(newarg=1)
756
757
Raymond Hettinger40f62172002-12-29 23:03:38 +0000758if __name__ == "__main__":
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300759 unittest.main()