blob: 9c1383d7db57376327389e77305c4b516194b34c [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
Raymond Hettingere8f1e002016-09-06 17:15:29 -070010from fractions import Fraction
Tim Peters46c04e12002-05-05 20:40:00 +000011
Ezio Melotti3e4a98b2013-04-19 05:45:27 +030012class TestBasicOps:
Raymond Hettinger40f62172002-12-29 23:03:38 +000013 # 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"""
Guido van Rossum805365e2007-05-07 22:24:25 +000019 return [self.gen.random() for i in range(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):
Mark Dickinson95aeae02012-06-24 11:05:30 +010038 # Seed value with a negative hash.
39 class MySeed(object):
40 def __hash__(self):
41 return -1729
Guido van Rossume2a383d2007-01-15 16:59:06 +000042 for arg in [None, 0, 0, 1, 1, -1, -1, 10**20, -(10**20),
Mark Dickinson95aeae02012-06-24 11:05:30 +010043 3.14, 1+2j, 'a', tuple('abc'), MySeed()]:
Raymond Hettinger40f62172002-12-29 23:03:38 +000044 self.gen.seed(arg)
Guido van Rossum805365e2007-05-07 22:24:25 +000045 for arg in [list(range(3)), dict(one=1)]:
Raymond Hettinger40f62172002-12-29 23:03:38 +000046 self.assertRaises(TypeError, self.gen.seed, arg)
Raymond Hettingerf763a722010-09-07 00:38:15 +000047 self.assertRaises(TypeError, self.gen.seed, 1, 2, 3, 4)
Raymond Hettinger58335872004-07-09 14:26:18 +000048 self.assertRaises(TypeError, type(self.gen), [])
Raymond Hettinger40f62172002-12-29 23:03:38 +000049
R David Murraye3e1c172013-04-02 12:47:23 -040050 @unittest.mock.patch('random._urandom') # os.urandom
51 def test_seed_when_randomness_source_not_found(self, urandom_mock):
52 # Random.seed() uses time.time() when an operating system specific
53 # randomness source is not found. To test this on machines were it
54 # exists, run the above test, test_seedargs(), again after mocking
55 # os.urandom() so that it raises the exception expected when the
56 # randomness source is not available.
57 urandom_mock.side_effect = NotImplementedError
58 self.test_seedargs()
59
Antoine Pitrou5e394332012-11-04 02:10:33 +010060 def test_shuffle(self):
61 shuffle = self.gen.shuffle
62 lst = []
63 shuffle(lst)
64 self.assertEqual(lst, [])
65 lst = [37]
66 shuffle(lst)
67 self.assertEqual(lst, [37])
68 seqs = [list(range(n)) for n in range(10)]
69 shuffled_seqs = [list(range(n)) for n in range(10)]
70 for shuffled_seq in shuffled_seqs:
71 shuffle(shuffled_seq)
72 for (seq, shuffled_seq) in zip(seqs, shuffled_seqs):
73 self.assertEqual(len(seq), len(shuffled_seq))
74 self.assertEqual(set(seq), set(shuffled_seq))
Antoine Pitrou5e394332012-11-04 02:10:33 +010075 # The above tests all would pass if the shuffle was a
76 # no-op. The following non-deterministic test covers that. It
77 # asserts that the shuffled sequence of 1000 distinct elements
78 # must be different from the original one. Although there is
79 # mathematically a non-zero probability that this could
80 # actually happen in a genuinely random shuffle, it is
81 # completely negligible, given that the number of possible
82 # permutations of 1000 objects is 1000! (factorial of 1000),
83 # which is considerably larger than the number of atoms in the
84 # universe...
85 lst = list(range(1000))
86 shuffled_lst = list(range(1000))
87 shuffle(shuffled_lst)
88 self.assertTrue(lst != shuffled_lst)
89 shuffle(lst)
90 self.assertTrue(lst != shuffled_lst)
91
Raymond Hettingerdc4872e2010-09-07 10:06:56 +000092 def test_choice(self):
93 choice = self.gen.choice
94 with self.assertRaises(IndexError):
95 choice([])
96 self.assertEqual(choice([50]), 50)
97 self.assertIn(choice([25, 75]), [25, 75])
98
Raymond Hettinger40f62172002-12-29 23:03:38 +000099 def test_sample(self):
100 # For the entire allowable range of 0 <= k <= N, validate that
101 # the sample is of the correct length and contains only unique items
102 N = 100
Guido van Rossum805365e2007-05-07 22:24:25 +0000103 population = range(N)
104 for k in range(N+1):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000105 s = self.gen.sample(population, k)
106 self.assertEqual(len(s), k)
Raymond Hettingera690a992003-11-16 16:17:49 +0000107 uniq = set(s)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000108 self.assertEqual(len(uniq), k)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000109 self.assertTrue(uniq <= set(population))
Raymond Hettinger8ec78812003-01-04 05:55:11 +0000110 self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
R David Murraye3e1c172013-04-02 12:47:23 -0400111 # Exception raised if size of sample exceeds that of population
112 self.assertRaises(ValueError, self.gen.sample, population, N+1)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000113
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000114 def test_sample_distribution(self):
115 # For the entire allowable range of 0 <= k <= N, validate that
116 # sample generates all possible permutations
117 n = 5
118 pop = range(n)
119 trials = 10000 # large num prevents false negatives without slowing normal case
120 def factorial(n):
Guido van Rossum89da5d72006-08-22 00:21:25 +0000121 if n == 0:
122 return 1
123 return n * factorial(n - 1)
Guido van Rossum805365e2007-05-07 22:24:25 +0000124 for k in range(n):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000125 expected = factorial(n) // factorial(n-k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000126 perms = {}
Guido van Rossum805365e2007-05-07 22:24:25 +0000127 for i in range(trials):
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000128 perms[tuple(self.gen.sample(pop, k))] = None
129 if len(perms) == expected:
130 break
131 else:
132 self.fail()
133
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000134 def test_sample_inputs(self):
135 # SF bug #801342 -- population can be any iterable defining __len__()
Raymond Hettingera690a992003-11-16 16:17:49 +0000136 self.gen.sample(set(range(20)), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000137 self.gen.sample(range(20), 2)
Guido van Rossum805365e2007-05-07 22:24:25 +0000138 self.gen.sample(range(20), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000139 self.gen.sample(str('abcdefghijklmnopqrst'), 2)
140 self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
141
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000142 def test_sample_on_dicts(self):
Raymond Hettinger1acde192008-01-14 01:00:53 +0000143 self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000144
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700145 def test_choices(self):
146 choices = self.gen.choices
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700147 data = ['red', 'green', 'blue', 'yellow']
148 str_data = 'abcd'
149 range_data = range(4)
150 set_data = set(range(4))
151
152 # basic functionality
153 for sample in [
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700154 choices(5, data),
155 choices(5, data, range(4)),
156 choices(k=5, population=data, weights=range(4)),
157 choices(k=5, population=data, cum_weights=range(4)),
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700158 ]:
159 self.assertEqual(len(sample), 5)
160 self.assertEqual(type(sample), list)
161 self.assertTrue(set(sample) <= set(data))
162
163 # test argument handling
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700164 with self.assertRaises(TypeError): # missing arguments
165 choices(2)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700166
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700167 self.assertEqual(choices(0, data), []) # k == 0
168 self.assertEqual(choices(-1, data), []) # negative k behaves like ``[0] * -1``
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700169 with self.assertRaises(TypeError):
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700170 choices(2.5, data) # k is a float
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700171
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700172 self.assertTrue(set(choices(5, str_data)) <= set(str_data)) # population is a string sequence
173 self.assertTrue(set(choices(5, range_data)) <= set(range_data)) # population is a range
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700174 with self.assertRaises(TypeError):
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700175 choices(2.5, set_data) # population is not a sequence
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700176
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700177 self.assertTrue(set(choices(5, data, None)) <= set(data)) # weights is None
178 self.assertTrue(set(choices(5, data, weights=None)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700179 with self.assertRaises(ValueError):
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700180 choices(5, data, [1,2]) # len(weights) != len(population)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700181 with self.assertRaises(IndexError):
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700182 choices(5, data, [0]*4) # weights sum to zero
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700183 with self.assertRaises(TypeError):
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700184 choices(5, data, 10) # non-iterable weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700185 with self.assertRaises(TypeError):
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700186 choices(5, data, [None]*4) # non-numeric weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700187 for weights in [
188 [15, 10, 25, 30], # integer weights
189 [15.1, 10.2, 25.2, 30.3], # float weights
190 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional weights
191 [True, False, True, False] # booleans (include / exclude)
192 ]:
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700193 self.assertTrue(set(choices(5, data, weights)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700194
195 with self.assertRaises(ValueError):
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700196 choices(5, data, cum_weights=[1,2]) # len(weights) != len(population)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700197 with self.assertRaises(IndexError):
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700198 choices(5, data, cum_weights=[0]*4) # cum_weights sum to zero
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700199 with self.assertRaises(TypeError):
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700200 choices(5, data, cum_weights=10) # non-iterable cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700201 with self.assertRaises(TypeError):
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700202 choices(5, data, cum_weights=[None]*4) # non-numeric cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700203 with self.assertRaises(TypeError):
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700204 choices(5, data, range(4), cum_weights=range(4)) # both weights and cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700205 for weights in [
206 [15, 10, 25, 30], # integer cum_weights
207 [15.1, 10.2, 25.2, 30.3], # float cum_weights
208 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional cum_weights
209 ]:
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700210 self.assertTrue(set(choices(5, data, cum_weights=weights)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700211
Raymond Hettinger40f62172002-12-29 23:03:38 +0000212 def test_gauss(self):
213 # Ensure that the seed() method initializes all the hidden state. In
214 # particular, through 2.2.1 it failed to reset a piece of state used
215 # by (and only by) the .gauss() method.
216
217 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
218 self.gen.seed(seed)
219 x1 = self.gen.random()
220 y1 = self.gen.gauss(0, 1)
221
222 self.gen.seed(seed)
223 x2 = self.gen.random()
224 y2 = self.gen.gauss(0, 1)
225
226 self.assertEqual(x1, x2)
227 self.assertEqual(y1, y2)
228
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000229 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200230 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
231 state = pickle.dumps(self.gen, proto)
232 origseq = [self.gen.random() for i in range(10)]
233 newgen = pickle.loads(state)
234 restoredseq = [newgen.random() for i in range(10)]
235 self.assertEqual(origseq, restoredseq)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000236
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000237 def test_bug_1727780(self):
238 # verify that version-2-pickles can be loaded
239 # fine, whether they are created on 32-bit or 64-bit
240 # platforms, and that version-3-pickles load fine.
241 files = [("randv2_32.pck", 780),
242 ("randv2_64.pck", 866),
243 ("randv3.pck", 343)]
244 for file, value in files:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000245 f = open(support.findfile(file),"rb")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000246 r = pickle.load(f)
247 f.close()
Raymond Hettinger05156612010-09-07 04:44:52 +0000248 self.assertEqual(int(r.random()*1000), value)
249
250 def test_bug_9025(self):
251 # Had problem with an uneven distribution in int(n*random())
252 # Verify the fix by checking that distributions fall within expectations.
253 n = 100000
254 randrange = self.gen.randrange
255 k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n))
256 self.assertTrue(0.30 < k/n < .37, (k/n))
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000257
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300258try:
259 random.SystemRandom().random()
260except NotImplementedError:
261 SystemRandom_available = False
262else:
263 SystemRandom_available = True
264
265@unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available")
266class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000267 gen = random.SystemRandom()
Raymond Hettinger356a4592004-08-30 06:14:31 +0000268
269 def test_autoseed(self):
270 # Doesn't need to do anything except not fail
271 self.gen.seed()
272
273 def test_saverestore(self):
274 self.assertRaises(NotImplementedError, self.gen.getstate)
275 self.assertRaises(NotImplementedError, self.gen.setstate, None)
276
277 def test_seedargs(self):
278 # Doesn't need to do anything except not fail
279 self.gen.seed(100)
280
Raymond Hettinger356a4592004-08-30 06:14:31 +0000281 def test_gauss(self):
282 self.gen.gauss_next = None
283 self.gen.seed(100)
284 self.assertEqual(self.gen.gauss_next, None)
285
286 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200287 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
288 self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000289
290 def test_53_bits_per_float(self):
291 # This should pass whenever a C double has 53 bit precision.
292 span = 2 ** 53
293 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000294 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000295 cum |= int(self.gen.random() * span)
296 self.assertEqual(cum, span-1)
297
298 def test_bigrand(self):
299 # The randrange routine should build-up the required number of bits
300 # in stages so that all bit positions are active.
301 span = 2 ** 500
302 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000303 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000304 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000305 self.assertTrue(0 <= r < span)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000306 cum |= r
307 self.assertEqual(cum, span-1)
308
309 def test_bigrand_ranges(self):
310 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600311 start = self.gen.randrange(2 ** (i-2))
312 stop = self.gen.randrange(2 ** i)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000313 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600314 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000315 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000316
317 def test_rangelimits(self):
318 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
319 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000320 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000321
R David Murraye3e1c172013-04-02 12:47:23 -0400322 def test_randrange_nonunit_step(self):
323 rint = self.gen.randrange(0, 10, 2)
324 self.assertIn(rint, (0, 2, 4, 6, 8))
325 rint = self.gen.randrange(0, 2, 2)
326 self.assertEqual(rint, 0)
327
328 def test_randrange_errors(self):
329 raises = partial(self.assertRaises, ValueError, self.gen.randrange)
330 # Empty range
331 raises(3, 3)
332 raises(-721)
333 raises(0, 100, -12)
334 # Non-integer start/stop
335 raises(3.14159)
336 raises(0, 2.71828)
337 # Zero and non-integer step
338 raises(0, 42, 0)
339 raises(0, 42, 3.14159)
340
Raymond Hettinger356a4592004-08-30 06:14:31 +0000341 def test_genrandbits(self):
342 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000343 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000344 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000345
346 # Verify all bits active
347 getbits = self.gen.getrandbits
348 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
349 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000350 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000351 cum |= getbits(span)
352 self.assertEqual(cum, 2**span-1)
353
354 # Verify argument checking
355 self.assertRaises(TypeError, self.gen.getrandbits)
356 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
357 self.assertRaises(ValueError, self.gen.getrandbits, 0)
358 self.assertRaises(ValueError, self.gen.getrandbits, -1)
359 self.assertRaises(TypeError, self.gen.getrandbits, 10.1)
360
361 def test_randbelow_logic(self, _log=log, int=int):
362 # check bitcount transition points: 2**i and 2**(i+1)-1
363 # show that: k = int(1.001 + _log(n, 2))
364 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000365 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000366 n = 1 << i # check an exact power of two
Raymond Hettinger356a4592004-08-30 06:14:31 +0000367 numbits = i+1
368 k = int(1.00001 + _log(n, 2))
369 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000370 self.assertEqual(n, 2**(k-1))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000371
372 n += n - 1 # check 1 below the next power of two
373 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000374 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000375 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000376
377 n -= n >> 15 # check a little farther below the next power of two
378 k = int(1.00001 + _log(n, 2))
379 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000380 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger356a4592004-08-30 06:14:31 +0000381
382
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300383class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000384 gen = random.Random()
385
Raymond Hettingerf763a722010-09-07 00:38:15 +0000386 def test_guaranteed_stable(self):
387 # These sequences are guaranteed to stay the same across versions of python
388 self.gen.seed(3456147, version=1)
389 self.assertEqual([self.gen.random().hex() for i in range(4)],
390 ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1',
391 '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000392 self.gen.seed("the quick brown fox", version=2)
393 self.assertEqual([self.gen.random().hex() for i in range(4)],
Raymond Hettinger3fcf0022010-12-08 01:13:53 +0000394 ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
395 '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000396
Raymond Hettingerc7bab7c2016-08-31 15:01:08 -0700397 def test_bug_27706(self):
398 # Verify that version 1 seeds are unaffected by hash randomization
399
400 self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177
401 self.assertEqual([self.gen.random().hex() for i in range(4)],
402 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
403 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
404
405 self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789
406 self.assertEqual([self.gen.random().hex() for i in range(4)],
407 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
408 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
409
410 self.gen.seed('', version=1) # hash('') == 0
411 self.assertEqual([self.gen.random().hex() for i in range(4)],
412 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
413 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
414
Raymond Hettinger58335872004-07-09 14:26:18 +0000415 def test_setstate_first_arg(self):
416 self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
417
418 def test_setstate_middle_arg(self):
419 # Wrong type, s/b tuple
420 self.assertRaises(TypeError, self.gen.setstate, (2, None, None))
421 # Wrong length, s/b 625
422 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None))
423 # Wrong type, s/b tuple of 625 ints
424 self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None))
425 # Last element s/b an int also
426 self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None))
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300427 # Last element s/b between 0 and 624
428 with self.assertRaises((ValueError, OverflowError)):
429 self.gen.setstate((2, (1,)*624+(625,), None))
430 with self.assertRaises((ValueError, OverflowError)):
431 self.gen.setstate((2, (1,)*624+(-1,), None))
Raymond Hettinger58335872004-07-09 14:26:18 +0000432
R David Murraye3e1c172013-04-02 12:47:23 -0400433 # Little trick to make "tuple(x % (2**32) for x in internalstate)"
434 # raise ValueError. I cannot think of a simple way to achieve this, so
435 # I am opting for using a generator as the middle argument of setstate
436 # which attempts to cast a NaN to integer.
437 state_values = self.gen.getstate()[1]
438 state_values = list(state_values)
439 state_values[-1] = float('nan')
440 state = (int(x) for x in state_values)
441 self.assertRaises(TypeError, self.gen.setstate, (2, state, None))
442
Raymond Hettinger40f62172002-12-29 23:03:38 +0000443 def test_referenceImplementation(self):
444 # Compare the python implementation with results from the original
445 # code. Create 2000 53-bit precision random floats. Compare only
446 # the last ten entries to show that the independent implementations
447 # are tracking. Here is the main() function needed to create the
448 # list of expected random numbers:
449 # void main(void){
450 # int i;
451 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
452 # init_by_array(init, length);
453 # for (i=0; i<2000; i++) {
454 # printf("%.15f ", genrand_res53());
455 # if (i%5==4) printf("\n");
456 # }
457 # }
458 expected = [0.45839803073713259,
459 0.86057815201978782,
460 0.92848331726782152,
461 0.35932681119782461,
462 0.081823493762449573,
463 0.14332226470169329,
464 0.084297823823520024,
465 0.53814864671831453,
466 0.089215024911993401,
467 0.78486196105372907]
468
Guido van Rossume2a383d2007-01-15 16:59:06 +0000469 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000470 actual = self.randomlist(2000)[-10:]
471 for a, e in zip(actual, expected):
472 self.assertAlmostEqual(a,e,places=14)
473
474 def test_strong_reference_implementation(self):
475 # Like test_referenceImplementation, but checks for exact bit-level
476 # equality. This should pass on any box where C double contains
477 # at least 53 bits of precision (the underlying algorithm suffers
478 # no rounding errors -- all results are exact).
479 from math import ldexp
480
Guido van Rossume2a383d2007-01-15 16:59:06 +0000481 expected = [0x0eab3258d2231f,
482 0x1b89db315277a5,
483 0x1db622a5518016,
484 0x0b7f9af0d575bf,
485 0x029e4c4db82240,
486 0x04961892f5d673,
487 0x02b291598e4589,
488 0x11388382c15694,
489 0x02dad977c9e1fe,
490 0x191d96d4d334c6]
491 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000492 actual = self.randomlist(2000)[-10:]
493 for a, e in zip(actual, expected):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000494 self.assertEqual(int(ldexp(a, 53)), e)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000495
496 def test_long_seed(self):
497 # This is most interesting to run in debug mode, just to make sure
498 # nothing blows up. Under the covers, a dynamically resized array
499 # is allocated, consuming space proportional to the number of bits
500 # in the seed. Unfortunately, that's a quadratic-time algorithm,
501 # so don't make this horribly big.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000502 seed = (1 << (10000 * 8)) - 1 # about 10K bytes
Raymond Hettinger40f62172002-12-29 23:03:38 +0000503 self.gen.seed(seed)
504
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000505 def test_53_bits_per_float(self):
506 # This should pass whenever a C double has 53 bit precision.
507 span = 2 ** 53
508 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000509 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000510 cum |= int(self.gen.random() * span)
511 self.assertEqual(cum, span-1)
512
513 def test_bigrand(self):
514 # The randrange routine should build-up the required number of bits
515 # in stages so that all bit positions are active.
516 span = 2 ** 500
517 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000518 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000519 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000520 self.assertTrue(0 <= r < span)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000521 cum |= r
522 self.assertEqual(cum, span-1)
523
524 def test_bigrand_ranges(self):
525 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600526 start = self.gen.randrange(2 ** (i-2))
527 stop = self.gen.randrange(2 ** i)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000528 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600529 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000530 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000531
532 def test_rangelimits(self):
533 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
Raymond Hettingera690a992003-11-16 16:17:49 +0000534 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000535 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000536
537 def test_genrandbits(self):
538 # Verify cross-platform repeatability
539 self.gen.seed(1234567)
540 self.assertEqual(self.gen.getrandbits(100),
Guido van Rossume2a383d2007-01-15 16:59:06 +0000541 97904845777343510404718956115)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000542 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000543 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000544 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000545
546 # Verify all bits active
547 getbits = self.gen.getrandbits
548 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
549 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000550 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000551 cum |= getbits(span)
552 self.assertEqual(cum, 2**span-1)
553
Raymond Hettinger58335872004-07-09 14:26:18 +0000554 # Verify argument checking
555 self.assertRaises(TypeError, self.gen.getrandbits)
556 self.assertRaises(TypeError, self.gen.getrandbits, 'a')
557 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
558 self.assertRaises(ValueError, self.gen.getrandbits, 0)
559 self.assertRaises(ValueError, self.gen.getrandbits, -1)
560
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000561 def test_randbelow_logic(self, _log=log, int=int):
562 # check bitcount transition points: 2**i and 2**(i+1)-1
563 # show that: k = int(1.001 + _log(n, 2))
564 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000565 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000566 n = 1 << i # check an exact power of two
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000567 numbits = i+1
568 k = int(1.00001 + _log(n, 2))
569 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000570 self.assertEqual(n, 2**(k-1))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000571
572 n += n - 1 # check 1 below the next power of two
573 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000574 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000575 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000576
577 n -= n >> 15 # check a little farther below the next power of two
578 k = int(1.00001 + _log(n, 2))
579 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000580 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000581
R David Murraye3e1c172013-04-02 12:47:23 -0400582 @unittest.mock.patch('random.Random.random')
Martin Pantere26da7c2016-06-02 10:07:09 +0000583 def test_randbelow_overridden_random(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400584 # Random._randbelow() can only use random() when the built-in one
585 # has been overridden but no new getrandbits() method was supplied.
586 random_mock.side_effect = random.SystemRandom().random
587 maxsize = 1<<random.BPF
588 with warnings.catch_warnings():
589 warnings.simplefilter("ignore", UserWarning)
590 # Population range too large (n >= maxsize)
591 self.gen._randbelow(maxsize+1, maxsize = maxsize)
592 self.gen._randbelow(5640, maxsize = maxsize)
593
594 # This might be going too far to test a single line, but because of our
595 # noble aim of achieving 100% test coverage we need to write a case in
596 # which the following line in Random._randbelow() gets executed:
597 #
598 # rem = maxsize % n
599 # limit = (maxsize - rem) / maxsize
600 # r = random()
601 # while r >= limit:
602 # r = random() # <== *This line* <==<
603 #
604 # Therefore, to guarantee that the while loop is executed at least
605 # once, we need to mock random() so that it returns a number greater
606 # than 'limit' the first time it gets called.
607
608 n = 42
609 epsilon = 0.01
610 limit = (maxsize - (maxsize % n)) / maxsize
611 random_mock.side_effect = [limit + epsilon, limit - epsilon]
612 self.gen._randbelow(n, maxsize = maxsize)
613
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000614 def test_randrange_bug_1590891(self):
615 start = 1000000000000
616 stop = -100000000000000000000
617 step = -200
618 x = self.gen.randrange(start, stop, step)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000619 self.assertTrue(stop < x <= start)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000620 self.assertEqual((x+stop)%step, 0)
621
Raymond Hettinger2d0c2562009-02-19 09:53:18 +0000622def gamma(z, sqrt2pi=(2.0*pi)**0.5):
623 # Reflection to right half of complex plane
624 if z < 0.5:
625 return pi / sin(pi*z) / gamma(1.0-z)
626 # Lanczos approximation with g=7
627 az = z + (7.0 - 0.5)
628 return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
629 0.9999999999995183,
630 676.5203681218835 / z,
631 -1259.139216722289 / (z+1.0),
632 771.3234287757674 / (z+2.0),
633 -176.6150291498386 / (z+3.0),
634 12.50734324009056 / (z+4.0),
635 -0.1385710331296526 / (z+5.0),
636 0.9934937113930748e-05 / (z+6.0),
637 0.1659470187408462e-06 / (z+7.0),
638 ])
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000639
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000640class TestDistributions(unittest.TestCase):
641 def test_zeroinputs(self):
642 # Verify that distributions can handle a series of zero inputs'
643 g = random.Random()
Guido van Rossum805365e2007-05-07 22:24:25 +0000644 x = [g.random() for i in range(50)] + [0.0]*5
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000645 g.random = x[:].pop; g.uniform(1,10)
646 g.random = x[:].pop; g.paretovariate(1.0)
647 g.random = x[:].pop; g.expovariate(1.0)
648 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200649 g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000650 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
651 g.random = x[:].pop; g.gauss(0.0, 1.0)
652 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
653 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
654 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
655 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
656 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
657 g.random = x[:].pop; g.betavariate(3.0, 3.0)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000658 g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000659
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000660 def test_avg_std(self):
661 # Use integration to test distribution average and standard deviation.
662 # Only works for distributions which do not consume variates in pairs
663 g = random.Random()
664 N = 5000
Guido van Rossum805365e2007-05-07 22:24:25 +0000665 x = [i/float(N) for i in range(1,N)]
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000666 for variate, args, mu, sigmasqrd in [
667 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
Christian Heimesfe337bf2008-03-23 21:54:12 +0000668 (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 +0000669 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200670 (g.vonmisesvariate, (1.23, 0), pi, pi**2/3),
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000671 (g.paretovariate, (5.0,), 5.0/(5.0-1),
672 5.0/((5.0-1)**2*(5.0-2))),
673 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
674 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
675 g.random = x[:].pop
676 y = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000677 for i in range(len(x)):
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000678 try:
679 y.append(variate(*args))
680 except IndexError:
681 pass
682 s1 = s2 = 0
683 for e in y:
684 s1 += e
685 s2 += (e - mu) ** 2
686 N = len(y)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200687 self.assertAlmostEqual(s1/N, mu, places=2,
688 msg='%s%r' % (variate.__name__, args))
689 self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
690 msg='%s%r' % (variate.__name__, args))
691
692 def test_constant(self):
693 g = random.Random()
694 N = 100
695 for variate, args, expected in [
696 (g.uniform, (10.0, 10.0), 10.0),
697 (g.triangular, (10.0, 10.0), 10.0),
Raymond Hettinger978c6ab2014-05-25 17:25:27 -0700698 (g.triangular, (10.0, 10.0, 10.0), 10.0),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200699 (g.expovariate, (float('inf'),), 0.0),
700 (g.vonmisesvariate, (3.0, float('inf')), 3.0),
701 (g.gauss, (10.0, 0.0), 10.0),
702 (g.lognormvariate, (0.0, 0.0), 1.0),
703 (g.lognormvariate, (-float('inf'), 0.0), 0.0),
704 (g.normalvariate, (10.0, 0.0), 10.0),
705 (g.paretovariate, (float('inf'),), 1.0),
706 (g.weibullvariate, (10.0, float('inf')), 10.0),
707 (g.weibullvariate, (0.0, 10.0), 0.0),
708 ]:
709 for i in range(N):
710 self.assertEqual(variate(*args), expected)
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000711
Mark Dickinsonbe5f9192013-02-10 14:16:10 +0000712 def test_von_mises_range(self):
713 # Issue 17149: von mises variates were not consistently in the
714 # range [0, 2*PI].
715 g = random.Random()
716 N = 100
717 for mu in 0.0, 0.1, 3.1, 6.2:
718 for kappa in 0.0, 2.3, 500.0:
719 for _ in range(N):
720 sample = g.vonmisesvariate(mu, kappa)
721 self.assertTrue(
722 0 <= sample <= random.TWOPI,
723 msg=("vonmisesvariate({}, {}) produced a result {} out"
724 " of range [0, 2*pi]").format(mu, kappa, sample))
725
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200726 def test_von_mises_large_kappa(self):
727 # Issue #17141: vonmisesvariate() was hang for large kappas
728 random.vonmisesvariate(0, 1e15)
729 random.vonmisesvariate(0, 1e100)
730
R David Murraye3e1c172013-04-02 12:47:23 -0400731 def test_gammavariate_errors(self):
732 # Both alpha and beta must be > 0.0
733 self.assertRaises(ValueError, random.gammavariate, -1, 3)
734 self.assertRaises(ValueError, random.gammavariate, 0, 2)
735 self.assertRaises(ValueError, random.gammavariate, 2, 0)
736 self.assertRaises(ValueError, random.gammavariate, 1, -3)
737
738 @unittest.mock.patch('random.Random.random')
739 def test_gammavariate_full_code_coverage(self, random_mock):
740 # There are three different possibilities in the current implementation
741 # of random.gammavariate(), depending on the value of 'alpha'. What we
742 # are going to do here is to fix the values returned by random() to
743 # generate test cases that provide 100% line coverage of the method.
744
745 # #1: alpha > 1.0: we want the first random number to be outside the
746 # [1e-7, .9999999] range, so that the continue statement executes
747 # once. The values of u1 and u2 will be 0.5 and 0.3, respectively.
748 random_mock.side_effect = [1e-8, 0.5, 0.3]
749 returned_value = random.gammavariate(1.1, 2.3)
750 self.assertAlmostEqual(returned_value, 2.53)
751
752 # #2: alpha == 1: first random number less than 1e-7 to that the body
753 # of the while loop executes once. Then random.random() returns 0.45,
754 # which causes while to stop looping and the algorithm to terminate.
755 random_mock.side_effect = [1e-8, 0.45]
756 returned_value = random.gammavariate(1.0, 3.14)
757 self.assertAlmostEqual(returned_value, 2.507314166123803)
758
759 # #3: 0 < alpha < 1. This is the most complex region of code to cover,
760 # as there are multiple if-else statements. Let's take a look at the
761 # source code, and determine the values that we need accordingly:
762 #
763 # while 1:
764 # u = random()
765 # b = (_e + alpha)/_e
766 # p = b*u
767 # if p <= 1.0: # <=== (A)
768 # x = p ** (1.0/alpha)
769 # else: # <=== (B)
770 # x = -_log((b-p)/alpha)
771 # u1 = random()
772 # if p > 1.0: # <=== (C)
773 # if u1 <= x ** (alpha - 1.0): # <=== (D)
774 # break
775 # elif u1 <= _exp(-x): # <=== (E)
776 # break
777 # return x * beta
778 #
779 # First, we want (A) to be True. For that we need that:
780 # b*random() <= 1.0
781 # r1 = random() <= 1.0 / b
782 #
783 # We now get to the second if-else branch, and here, since p <= 1.0,
784 # (C) is False and we take the elif branch, (E). For it to be True,
785 # so that the break is executed, we need that:
786 # r2 = random() <= _exp(-x)
787 # r2 <= _exp(-(p ** (1.0/alpha)))
788 # r2 <= _exp(-((b*r1) ** (1.0/alpha)))
789
790 _e = random._e
791 _exp = random._exp
792 _log = random._log
793 alpha = 0.35
794 beta = 1.45
795 b = (_e + alpha)/_e
796 epsilon = 0.01
797
798 r1 = 0.8859296441566 # 1.0 / b
799 r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha)))
800
801 # These four "random" values result in the following trace:
802 # (A) True, (E) False --> [next iteration of while]
803 # (A) True, (E) True --> [while loop breaks]
804 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
805 returned_value = random.gammavariate(alpha, beta)
806 self.assertAlmostEqual(returned_value, 1.4499999999997544)
807
808 # Let's now make (A) be False. If this is the case, when we get to the
809 # second if-else 'p' is greater than 1, so (C) evaluates to True. We
810 # now encounter a second if statement, (D), which in order to execute
811 # must satisfy the following condition:
812 # r2 <= x ** (alpha - 1.0)
813 # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0)
814 # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0)
815 r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False
816 r2 = 0.9445400408898141
817
818 # And these four values result in the following trace:
819 # (B) and (C) True, (D) False --> [next iteration of while]
820 # (B) and (C) True, (D) True [while loop breaks]
821 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
822 returned_value = random.gammavariate(alpha, beta)
823 self.assertAlmostEqual(returned_value, 1.5830349561760781)
824
825 @unittest.mock.patch('random.Random.gammavariate')
826 def test_betavariate_return_zero(self, gammavariate_mock):
827 # betavariate() returns zero when the Gamma distribution
828 # that it uses internally returns this same value.
829 gammavariate_mock.return_value = 0.0
830 self.assertEqual(0.0, random.betavariate(2.71828, 3.14159))
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200831
Raymond Hettinger40f62172002-12-29 23:03:38 +0000832class TestModule(unittest.TestCase):
833 def testMagicConstants(self):
834 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
835 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
836 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
837 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
838
839 def test__all__(self):
840 # tests validity but not completeness of the __all__ list
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000841 self.assertTrue(set(random.__all__) <= set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000842
Thomas Woutersb2137042007-02-01 18:02:27 +0000843 def test_random_subclass_with_kwargs(self):
844 # SF bug #1486663 -- this used to erroneously raise a TypeError
845 class Subclass(random.Random):
846 def __init__(self, newarg=None):
847 random.Random.__init__(self)
848 Subclass(newarg=1)
849
850
Raymond Hettinger40f62172002-12-29 23:03:38 +0000851if __name__ == "__main__":
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300852 unittest.main()