Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 1 | import unittest |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 2 | import unittest.mock |
Tim Peters | 46c04e1 | 2002-05-05 20:40:00 +0000 | [diff] [blame] | 3 | import random |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 4 | import time |
Raymond Hettinger | 5f078ff | 2003-06-24 20:29:04 +0000 | [diff] [blame] | 5 | import pickle |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 6 | import warnings |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 7 | from functools import partial |
Georg Brandl | 1b37e87 | 2010-03-14 10:45:50 +0000 | [diff] [blame] | 8 | from math import log, exp, pi, fsum, sin |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 9 | from test import support |
Tim Peters | 46c04e1 | 2002-05-05 20:40:00 +0000 | [diff] [blame] | 10 | |
Ezio Melotti | 3e4a98b | 2013-04-19 05:45:27 +0300 | [diff] [blame] | 11 | class TestBasicOps: |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 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 Peters | 46c04e1 | 2002-05-05 20:40:00 +0000 | [diff] [blame] | 15 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 16 | def randomlist(self, n): |
| 17 | """Helper function to make a list of random numbers""" |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 18 | return [self.gen.random() for i in range(n)] |
Tim Peters | 46c04e1 | 2002-05-05 20:40:00 +0000 | [diff] [blame] | 19 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 20 | def test_autoseed(self): |
| 21 | self.gen.seed() |
| 22 | state1 = self.gen.getstate() |
Raymond Hettinger | 3081d59 | 2003-08-09 18:30:57 +0000 | [diff] [blame] | 23 | time.sleep(0.1) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 24 | self.gen.seed() # diffent seeds at different times |
| 25 | state2 = self.gen.getstate() |
| 26 | self.assertNotEqual(state1, state2) |
Tim Peters | 46c04e1 | 2002-05-05 20:40:00 +0000 | [diff] [blame] | 27 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 28 | 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 Dickinson | 95aeae0 | 2012-06-24 11:05:30 +0100 | [diff] [blame] | 37 | # Seed value with a negative hash. |
| 38 | class MySeed(object): |
| 39 | def __hash__(self): |
| 40 | return -1729 |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 41 | for arg in [None, 0, 0, 1, 1, -1, -1, 10**20, -(10**20), |
Mark Dickinson | 95aeae0 | 2012-06-24 11:05:30 +0100 | [diff] [blame] | 42 | 3.14, 1+2j, 'a', tuple('abc'), MySeed()]: |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 43 | self.gen.seed(arg) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 44 | for arg in [list(range(3)), dict(one=1)]: |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 45 | self.assertRaises(TypeError, self.gen.seed, arg) |
Raymond Hettinger | f763a72 | 2010-09-07 00:38:15 +0000 | [diff] [blame] | 46 | self.assertRaises(TypeError, self.gen.seed, 1, 2, 3, 4) |
Raymond Hettinger | 5833587 | 2004-07-09 14:26:18 +0000 | [diff] [blame] | 47 | self.assertRaises(TypeError, type(self.gen), []) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 48 | |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 49 | @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 Pitrou | 5e39433 | 2012-11-04 02:10:33 +0100 | [diff] [blame] | 59 | 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 Pitrou | 5e39433 | 2012-11-04 02:10:33 +0100 | [diff] [blame] | 74 | # 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 Hettinger | dc4872e | 2010-09-07 10:06:56 +0000 | [diff] [blame] | 91 | 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 Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 98 | 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 Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 102 | population = range(N) |
| 103 | for k in range(N+1): |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 104 | s = self.gen.sample(population, k) |
| 105 | self.assertEqual(len(s), k) |
Raymond Hettinger | a690a99 | 2003-11-16 16:17:49 +0000 | [diff] [blame] | 106 | uniq = set(s) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 107 | self.assertEqual(len(uniq), k) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 108 | self.assertTrue(uniq <= set(population)) |
Raymond Hettinger | 8ec7881 | 2003-01-04 05:55:11 +0000 | [diff] [blame] | 109 | self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0 |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 110 | # Exception raised if size of sample exceeds that of population |
| 111 | self.assertRaises(ValueError, self.gen.sample, population, N+1) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 112 | |
Raymond Hettinger | 7b0cf76 | 2003-01-17 17:23:23 +0000 | [diff] [blame] | 113 | 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 Rossum | 89da5d7 | 2006-08-22 00:21:25 +0000 | [diff] [blame] | 120 | if n == 0: |
| 121 | return 1 |
| 122 | return n * factorial(n - 1) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 123 | for k in range(n): |
Raymond Hettinger | ffdb8bb | 2004-09-27 15:29:05 +0000 | [diff] [blame] | 124 | expected = factorial(n) // factorial(n-k) |
Raymond Hettinger | 7b0cf76 | 2003-01-17 17:23:23 +0000 | [diff] [blame] | 125 | perms = {} |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 126 | for i in range(trials): |
Raymond Hettinger | 7b0cf76 | 2003-01-17 17:23:23 +0000 | [diff] [blame] | 127 | perms[tuple(self.gen.sample(pop, k))] = None |
| 128 | if len(perms) == expected: |
| 129 | break |
| 130 | else: |
| 131 | self.fail() |
| 132 | |
Raymond Hettinger | 66d09f1 | 2003-09-06 04:25:54 +0000 | [diff] [blame] | 133 | def test_sample_inputs(self): |
| 134 | # SF bug #801342 -- population can be any iterable defining __len__() |
Raymond Hettinger | a690a99 | 2003-11-16 16:17:49 +0000 | [diff] [blame] | 135 | self.gen.sample(set(range(20)), 2) |
Raymond Hettinger | 66d09f1 | 2003-09-06 04:25:54 +0000 | [diff] [blame] | 136 | self.gen.sample(range(20), 2) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 137 | self.gen.sample(range(20), 2) |
Raymond Hettinger | 66d09f1 | 2003-09-06 04:25:54 +0000 | [diff] [blame] | 138 | self.gen.sample(str('abcdefghijklmnopqrst'), 2) |
| 139 | self.gen.sample(tuple('abcdefghijklmnopqrst'), 2) |
| 140 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 141 | def test_sample_on_dicts(self): |
Raymond Hettinger | 1acde19 | 2008-01-14 01:00:53 +0000 | [diff] [blame] | 142 | self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 143 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 144 | 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 Hettinger | 5f078ff | 2003-06-24 20:29:04 +0000 | [diff] [blame] | 161 | def test_pickling(self): |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 162 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 163 | state = pickle.dumps(self.gen, proto) |
| 164 | origseq = [self.gen.random() for i in range(10)] |
| 165 | newgen = pickle.loads(state) |
| 166 | restoredseq = [newgen.random() for i in range(10)] |
| 167 | self.assertEqual(origseq, restoredseq) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 168 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 169 | def test_bug_1727780(self): |
| 170 | # verify that version-2-pickles can be loaded |
| 171 | # fine, whether they are created on 32-bit or 64-bit |
| 172 | # platforms, and that version-3-pickles load fine. |
| 173 | files = [("randv2_32.pck", 780), |
| 174 | ("randv2_64.pck", 866), |
| 175 | ("randv3.pck", 343)] |
| 176 | for file, value in files: |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 177 | f = open(support.findfile(file),"rb") |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 178 | r = pickle.load(f) |
| 179 | f.close() |
Raymond Hettinger | 0515661 | 2010-09-07 04:44:52 +0000 | [diff] [blame] | 180 | self.assertEqual(int(r.random()*1000), value) |
| 181 | |
| 182 | def test_bug_9025(self): |
| 183 | # Had problem with an uneven distribution in int(n*random()) |
| 184 | # Verify the fix by checking that distributions fall within expectations. |
| 185 | n = 100000 |
| 186 | randrange = self.gen.randrange |
| 187 | k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n)) |
| 188 | self.assertTrue(0.30 < k/n < .37, (k/n)) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 189 | |
Ezio Melotti | 3e4a98b | 2013-04-19 05:45:27 +0300 | [diff] [blame] | 190 | try: |
| 191 | random.SystemRandom().random() |
| 192 | except NotImplementedError: |
| 193 | SystemRandom_available = False |
| 194 | else: |
| 195 | SystemRandom_available = True |
| 196 | |
| 197 | @unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available") |
| 198 | class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase): |
Raymond Hettinger | 23f1241 | 2004-09-13 22:23:21 +0000 | [diff] [blame] | 199 | gen = random.SystemRandom() |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 200 | |
| 201 | def test_autoseed(self): |
| 202 | # Doesn't need to do anything except not fail |
| 203 | self.gen.seed() |
| 204 | |
| 205 | def test_saverestore(self): |
| 206 | self.assertRaises(NotImplementedError, self.gen.getstate) |
| 207 | self.assertRaises(NotImplementedError, self.gen.setstate, None) |
| 208 | |
| 209 | def test_seedargs(self): |
| 210 | # Doesn't need to do anything except not fail |
| 211 | self.gen.seed(100) |
| 212 | |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 213 | def test_gauss(self): |
| 214 | self.gen.gauss_next = None |
| 215 | self.gen.seed(100) |
| 216 | self.assertEqual(self.gen.gauss_next, None) |
| 217 | |
| 218 | def test_pickling(self): |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 219 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 220 | self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 221 | |
| 222 | def test_53_bits_per_float(self): |
| 223 | # This should pass whenever a C double has 53 bit precision. |
| 224 | span = 2 ** 53 |
| 225 | cum = 0 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 226 | for i in range(100): |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 227 | cum |= int(self.gen.random() * span) |
| 228 | self.assertEqual(cum, span-1) |
| 229 | |
| 230 | def test_bigrand(self): |
| 231 | # The randrange routine should build-up the required number of bits |
| 232 | # in stages so that all bit positions are active. |
| 233 | span = 2 ** 500 |
| 234 | cum = 0 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 235 | for i in range(100): |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 236 | r = self.gen.randrange(span) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 237 | self.assertTrue(0 <= r < span) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 238 | cum |= r |
| 239 | self.assertEqual(cum, span-1) |
| 240 | |
| 241 | def test_bigrand_ranges(self): |
| 242 | for i in [40,80, 160, 200, 211, 250, 375, 512, 550]: |
Zachary Ware | a6edea5 | 2013-11-26 14:50:10 -0600 | [diff] [blame] | 243 | start = self.gen.randrange(2 ** (i-2)) |
| 244 | stop = self.gen.randrange(2 ** i) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 245 | if stop <= start: |
Zachary Ware | a6edea5 | 2013-11-26 14:50:10 -0600 | [diff] [blame] | 246 | continue |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 247 | self.assertTrue(start <= self.gen.randrange(start, stop) < stop) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 248 | |
| 249 | def test_rangelimits(self): |
| 250 | for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]: |
| 251 | self.assertEqual(set(range(start,stop)), |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 252 | set([self.gen.randrange(start,stop) for i in range(100)])) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 253 | |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 254 | def test_randrange_nonunit_step(self): |
| 255 | rint = self.gen.randrange(0, 10, 2) |
| 256 | self.assertIn(rint, (0, 2, 4, 6, 8)) |
| 257 | rint = self.gen.randrange(0, 2, 2) |
| 258 | self.assertEqual(rint, 0) |
| 259 | |
| 260 | def test_randrange_errors(self): |
| 261 | raises = partial(self.assertRaises, ValueError, self.gen.randrange) |
| 262 | # Empty range |
| 263 | raises(3, 3) |
| 264 | raises(-721) |
| 265 | raises(0, 100, -12) |
| 266 | # Non-integer start/stop |
| 267 | raises(3.14159) |
| 268 | raises(0, 2.71828) |
| 269 | # Zero and non-integer step |
| 270 | raises(0, 42, 0) |
| 271 | raises(0, 42, 3.14159) |
| 272 | |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 273 | def test_genrandbits(self): |
| 274 | # Verify ranges |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 275 | for k in range(1, 1000): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 276 | self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 277 | |
| 278 | # Verify all bits active |
| 279 | getbits = self.gen.getrandbits |
| 280 | for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]: |
| 281 | cum = 0 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 282 | for i in range(100): |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 283 | cum |= getbits(span) |
| 284 | self.assertEqual(cum, 2**span-1) |
| 285 | |
| 286 | # Verify argument checking |
| 287 | self.assertRaises(TypeError, self.gen.getrandbits) |
| 288 | self.assertRaises(TypeError, self.gen.getrandbits, 1, 2) |
| 289 | self.assertRaises(ValueError, self.gen.getrandbits, 0) |
| 290 | self.assertRaises(ValueError, self.gen.getrandbits, -1) |
| 291 | self.assertRaises(TypeError, self.gen.getrandbits, 10.1) |
| 292 | |
| 293 | def test_randbelow_logic(self, _log=log, int=int): |
| 294 | # check bitcount transition points: 2**i and 2**(i+1)-1 |
| 295 | # show that: k = int(1.001 + _log(n, 2)) |
| 296 | # is equal to or one greater than the number of bits in n |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 297 | for i in range(1, 1000): |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 298 | n = 1 << i # check an exact power of two |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 299 | numbits = i+1 |
| 300 | k = int(1.00001 + _log(n, 2)) |
| 301 | self.assertEqual(k, numbits) |
Guido van Rossum | e61fd5b | 2007-07-11 12:20:59 +0000 | [diff] [blame] | 302 | self.assertEqual(n, 2**(k-1)) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 303 | |
| 304 | n += n - 1 # check 1 below the next power of two |
| 305 | k = int(1.00001 + _log(n, 2)) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 306 | self.assertIn(k, [numbits, numbits+1]) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 307 | self.assertTrue(2**k > n > 2**(k-2)) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 308 | |
| 309 | n -= n >> 15 # check a little farther below the next power of two |
| 310 | k = int(1.00001 + _log(n, 2)) |
| 311 | self.assertEqual(k, numbits) # note the stronger assertion |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 312 | self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 313 | |
| 314 | |
Ezio Melotti | 3e4a98b | 2013-04-19 05:45:27 +0300 | [diff] [blame] | 315 | class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase): |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 316 | gen = random.Random() |
| 317 | |
Raymond Hettinger | f763a72 | 2010-09-07 00:38:15 +0000 | [diff] [blame] | 318 | def test_guaranteed_stable(self): |
| 319 | # These sequences are guaranteed to stay the same across versions of python |
| 320 | self.gen.seed(3456147, version=1) |
| 321 | self.assertEqual([self.gen.random().hex() for i in range(4)], |
| 322 | ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1', |
| 323 | '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1']) |
Raymond Hettinger | f763a72 | 2010-09-07 00:38:15 +0000 | [diff] [blame] | 324 | self.gen.seed("the quick brown fox", version=2) |
| 325 | self.assertEqual([self.gen.random().hex() for i in range(4)], |
Raymond Hettinger | 3fcf002 | 2010-12-08 01:13:53 +0000 | [diff] [blame] | 326 | ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4', |
| 327 | '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1']) |
Raymond Hettinger | f763a72 | 2010-09-07 00:38:15 +0000 | [diff] [blame] | 328 | |
Raymond Hettinger | 5833587 | 2004-07-09 14:26:18 +0000 | [diff] [blame] | 329 | def test_setstate_first_arg(self): |
| 330 | self.assertRaises(ValueError, self.gen.setstate, (1, None, None)) |
| 331 | |
| 332 | def test_setstate_middle_arg(self): |
| 333 | # Wrong type, s/b tuple |
| 334 | self.assertRaises(TypeError, self.gen.setstate, (2, None, None)) |
| 335 | # Wrong length, s/b 625 |
| 336 | self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None)) |
| 337 | # Wrong type, s/b tuple of 625 ints |
| 338 | self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None)) |
| 339 | # Last element s/b an int also |
| 340 | self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None)) |
Serhiy Storchaka | 178f0b6 | 2015-07-24 09:02:53 +0300 | [diff] [blame] | 341 | # Last element s/b between 0 and 624 |
| 342 | with self.assertRaises((ValueError, OverflowError)): |
| 343 | self.gen.setstate((2, (1,)*624+(625,), None)) |
| 344 | with self.assertRaises((ValueError, OverflowError)): |
| 345 | self.gen.setstate((2, (1,)*624+(-1,), None)) |
Raymond Hettinger | 5833587 | 2004-07-09 14:26:18 +0000 | [diff] [blame] | 346 | |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 347 | # Little trick to make "tuple(x % (2**32) for x in internalstate)" |
| 348 | # raise ValueError. I cannot think of a simple way to achieve this, so |
| 349 | # I am opting for using a generator as the middle argument of setstate |
| 350 | # which attempts to cast a NaN to integer. |
| 351 | state_values = self.gen.getstate()[1] |
| 352 | state_values = list(state_values) |
| 353 | state_values[-1] = float('nan') |
| 354 | state = (int(x) for x in state_values) |
| 355 | self.assertRaises(TypeError, self.gen.setstate, (2, state, None)) |
| 356 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 357 | def test_referenceImplementation(self): |
| 358 | # Compare the python implementation with results from the original |
| 359 | # code. Create 2000 53-bit precision random floats. Compare only |
| 360 | # the last ten entries to show that the independent implementations |
| 361 | # are tracking. Here is the main() function needed to create the |
| 362 | # list of expected random numbers: |
| 363 | # void main(void){ |
| 364 | # int i; |
| 365 | # unsigned long init[4]={61731, 24903, 614, 42143}, length=4; |
| 366 | # init_by_array(init, length); |
| 367 | # for (i=0; i<2000; i++) { |
| 368 | # printf("%.15f ", genrand_res53()); |
| 369 | # if (i%5==4) printf("\n"); |
| 370 | # } |
| 371 | # } |
| 372 | expected = [0.45839803073713259, |
| 373 | 0.86057815201978782, |
| 374 | 0.92848331726782152, |
| 375 | 0.35932681119782461, |
| 376 | 0.081823493762449573, |
| 377 | 0.14332226470169329, |
| 378 | 0.084297823823520024, |
| 379 | 0.53814864671831453, |
| 380 | 0.089215024911993401, |
| 381 | 0.78486196105372907] |
| 382 | |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 383 | self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96)) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 384 | actual = self.randomlist(2000)[-10:] |
| 385 | for a, e in zip(actual, expected): |
| 386 | self.assertAlmostEqual(a,e,places=14) |
| 387 | |
| 388 | def test_strong_reference_implementation(self): |
| 389 | # Like test_referenceImplementation, but checks for exact bit-level |
| 390 | # equality. This should pass on any box where C double contains |
| 391 | # at least 53 bits of precision (the underlying algorithm suffers |
| 392 | # no rounding errors -- all results are exact). |
| 393 | from math import ldexp |
| 394 | |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 395 | expected = [0x0eab3258d2231f, |
| 396 | 0x1b89db315277a5, |
| 397 | 0x1db622a5518016, |
| 398 | 0x0b7f9af0d575bf, |
| 399 | 0x029e4c4db82240, |
| 400 | 0x04961892f5d673, |
| 401 | 0x02b291598e4589, |
| 402 | 0x11388382c15694, |
| 403 | 0x02dad977c9e1fe, |
| 404 | 0x191d96d4d334c6] |
| 405 | self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96)) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 406 | actual = self.randomlist(2000)[-10:] |
| 407 | for a, e in zip(actual, expected): |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 408 | self.assertEqual(int(ldexp(a, 53)), e) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 409 | |
| 410 | def test_long_seed(self): |
| 411 | # This is most interesting to run in debug mode, just to make sure |
| 412 | # nothing blows up. Under the covers, a dynamically resized array |
| 413 | # is allocated, consuming space proportional to the number of bits |
| 414 | # in the seed. Unfortunately, that's a quadratic-time algorithm, |
| 415 | # so don't make this horribly big. |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 416 | seed = (1 << (10000 * 8)) - 1 # about 10K bytes |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 417 | self.gen.seed(seed) |
| 418 | |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 419 | def test_53_bits_per_float(self): |
| 420 | # This should pass whenever a C double has 53 bit precision. |
| 421 | span = 2 ** 53 |
| 422 | cum = 0 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 423 | for i in range(100): |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 424 | cum |= int(self.gen.random() * span) |
| 425 | self.assertEqual(cum, span-1) |
| 426 | |
| 427 | def test_bigrand(self): |
| 428 | # The randrange routine should build-up the required number of bits |
| 429 | # in stages so that all bit positions are active. |
| 430 | span = 2 ** 500 |
| 431 | cum = 0 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 432 | for i in range(100): |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 433 | r = self.gen.randrange(span) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 434 | self.assertTrue(0 <= r < span) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 435 | cum |= r |
| 436 | self.assertEqual(cum, span-1) |
| 437 | |
| 438 | def test_bigrand_ranges(self): |
| 439 | for i in [40,80, 160, 200, 211, 250, 375, 512, 550]: |
Zachary Ware | a6edea5 | 2013-11-26 14:50:10 -0600 | [diff] [blame] | 440 | start = self.gen.randrange(2 ** (i-2)) |
| 441 | stop = self.gen.randrange(2 ** i) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 442 | if stop <= start: |
Zachary Ware | a6edea5 | 2013-11-26 14:50:10 -0600 | [diff] [blame] | 443 | continue |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 444 | self.assertTrue(start <= self.gen.randrange(start, stop) < stop) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 445 | |
| 446 | def test_rangelimits(self): |
| 447 | for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]: |
Raymond Hettinger | a690a99 | 2003-11-16 16:17:49 +0000 | [diff] [blame] | 448 | self.assertEqual(set(range(start,stop)), |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 449 | set([self.gen.randrange(start,stop) for i in range(100)])) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 450 | |
| 451 | def test_genrandbits(self): |
| 452 | # Verify cross-platform repeatability |
| 453 | self.gen.seed(1234567) |
| 454 | self.assertEqual(self.gen.getrandbits(100), |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 455 | 97904845777343510404718956115) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 456 | # Verify ranges |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 457 | for k in range(1, 1000): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 458 | self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 459 | |
| 460 | # Verify all bits active |
| 461 | getbits = self.gen.getrandbits |
| 462 | for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]: |
| 463 | cum = 0 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 464 | for i in range(100): |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 465 | cum |= getbits(span) |
| 466 | self.assertEqual(cum, 2**span-1) |
| 467 | |
Raymond Hettinger | 5833587 | 2004-07-09 14:26:18 +0000 | [diff] [blame] | 468 | # Verify argument checking |
| 469 | self.assertRaises(TypeError, self.gen.getrandbits) |
| 470 | self.assertRaises(TypeError, self.gen.getrandbits, 'a') |
| 471 | self.assertRaises(TypeError, self.gen.getrandbits, 1, 2) |
| 472 | self.assertRaises(ValueError, self.gen.getrandbits, 0) |
| 473 | self.assertRaises(ValueError, self.gen.getrandbits, -1) |
| 474 | |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 475 | def test_randbelow_logic(self, _log=log, int=int): |
| 476 | # check bitcount transition points: 2**i and 2**(i+1)-1 |
| 477 | # show that: k = int(1.001 + _log(n, 2)) |
| 478 | # is equal to or one greater than the number of bits in n |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 479 | for i in range(1, 1000): |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 480 | n = 1 << i # check an exact power of two |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 481 | numbits = i+1 |
| 482 | k = int(1.00001 + _log(n, 2)) |
| 483 | self.assertEqual(k, numbits) |
Guido van Rossum | e61fd5b | 2007-07-11 12:20:59 +0000 | [diff] [blame] | 484 | self.assertEqual(n, 2**(k-1)) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 485 | |
| 486 | n += n - 1 # check 1 below the next power of two |
| 487 | k = int(1.00001 + _log(n, 2)) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 488 | self.assertIn(k, [numbits, numbits+1]) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 489 | self.assertTrue(2**k > n > 2**(k-2)) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 490 | |
| 491 | n -= n >> 15 # check a little farther below the next power of two |
| 492 | k = int(1.00001 + _log(n, 2)) |
| 493 | self.assertEqual(k, numbits) # note the stronger assertion |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 494 | self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 495 | |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 496 | @unittest.mock.patch('random.Random.random') |
Martin Panter | e26da7c | 2016-06-02 10:07:09 +0000 | [diff] [blame] | 497 | def test_randbelow_overridden_random(self, random_mock): |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 498 | # Random._randbelow() can only use random() when the built-in one |
| 499 | # has been overridden but no new getrandbits() method was supplied. |
| 500 | random_mock.side_effect = random.SystemRandom().random |
| 501 | maxsize = 1<<random.BPF |
| 502 | with warnings.catch_warnings(): |
| 503 | warnings.simplefilter("ignore", UserWarning) |
| 504 | # Population range too large (n >= maxsize) |
| 505 | self.gen._randbelow(maxsize+1, maxsize = maxsize) |
| 506 | self.gen._randbelow(5640, maxsize = maxsize) |
| 507 | |
| 508 | # This might be going too far to test a single line, but because of our |
| 509 | # noble aim of achieving 100% test coverage we need to write a case in |
| 510 | # which the following line in Random._randbelow() gets executed: |
| 511 | # |
| 512 | # rem = maxsize % n |
| 513 | # limit = (maxsize - rem) / maxsize |
| 514 | # r = random() |
| 515 | # while r >= limit: |
| 516 | # r = random() # <== *This line* <==< |
| 517 | # |
| 518 | # Therefore, to guarantee that the while loop is executed at least |
| 519 | # once, we need to mock random() so that it returns a number greater |
| 520 | # than 'limit' the first time it gets called. |
| 521 | |
| 522 | n = 42 |
| 523 | epsilon = 0.01 |
| 524 | limit = (maxsize - (maxsize % n)) / maxsize |
| 525 | random_mock.side_effect = [limit + epsilon, limit - epsilon] |
| 526 | self.gen._randbelow(n, maxsize = maxsize) |
| 527 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 528 | def test_randrange_bug_1590891(self): |
| 529 | start = 1000000000000 |
| 530 | stop = -100000000000000000000 |
| 531 | step = -200 |
| 532 | x = self.gen.randrange(start, stop, step) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 533 | self.assertTrue(stop < x <= start) |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 534 | self.assertEqual((x+stop)%step, 0) |
| 535 | |
Raymond Hettinger | 2d0c256 | 2009-02-19 09:53:18 +0000 | [diff] [blame] | 536 | def gamma(z, sqrt2pi=(2.0*pi)**0.5): |
| 537 | # Reflection to right half of complex plane |
| 538 | if z < 0.5: |
| 539 | return pi / sin(pi*z) / gamma(1.0-z) |
| 540 | # Lanczos approximation with g=7 |
| 541 | az = z + (7.0 - 0.5) |
| 542 | return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([ |
| 543 | 0.9999999999995183, |
| 544 | 676.5203681218835 / z, |
| 545 | -1259.139216722289 / (z+1.0), |
| 546 | 771.3234287757674 / (z+2.0), |
| 547 | -176.6150291498386 / (z+3.0), |
| 548 | 12.50734324009056 / (z+4.0), |
| 549 | -0.1385710331296526 / (z+5.0), |
| 550 | 0.9934937113930748e-05 / (z+6.0), |
| 551 | 0.1659470187408462e-06 / (z+7.0), |
| 552 | ]) |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 553 | |
Raymond Hettinger | 15ec373 | 2003-01-05 01:08:34 +0000 | [diff] [blame] | 554 | class TestDistributions(unittest.TestCase): |
| 555 | def test_zeroinputs(self): |
| 556 | # Verify that distributions can handle a series of zero inputs' |
| 557 | g = random.Random() |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 558 | x = [g.random() for i in range(50)] + [0.0]*5 |
Raymond Hettinger | 15ec373 | 2003-01-05 01:08:34 +0000 | [diff] [blame] | 559 | g.random = x[:].pop; g.uniform(1,10) |
| 560 | g.random = x[:].pop; g.paretovariate(1.0) |
| 561 | g.random = x[:].pop; g.expovariate(1.0) |
| 562 | g.random = x[:].pop; g.weibullvariate(1.0, 1.0) |
Serhiy Storchaka | 6c22b1d | 2013-02-10 19:28:56 +0200 | [diff] [blame] | 563 | g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0) |
Raymond Hettinger | 15ec373 | 2003-01-05 01:08:34 +0000 | [diff] [blame] | 564 | g.random = x[:].pop; g.normalvariate(0.0, 1.0) |
| 565 | g.random = x[:].pop; g.gauss(0.0, 1.0) |
| 566 | g.random = x[:].pop; g.lognormvariate(0.0, 1.0) |
| 567 | g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0) |
| 568 | g.random = x[:].pop; g.gammavariate(0.01, 1.0) |
| 569 | g.random = x[:].pop; g.gammavariate(1.0, 1.0) |
| 570 | g.random = x[:].pop; g.gammavariate(200.0, 1.0) |
| 571 | g.random = x[:].pop; g.betavariate(3.0, 3.0) |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 572 | g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0) |
Raymond Hettinger | 15ec373 | 2003-01-05 01:08:34 +0000 | [diff] [blame] | 573 | |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 574 | def test_avg_std(self): |
| 575 | # Use integration to test distribution average and standard deviation. |
| 576 | # Only works for distributions which do not consume variates in pairs |
| 577 | g = random.Random() |
| 578 | N = 5000 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 579 | x = [i/float(N) for i in range(1,N)] |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 580 | for variate, args, mu, sigmasqrd in [ |
| 581 | (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12), |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 582 | (g.triangular, (0.0, 1.0, 1.0/3.0), 4.0/9.0, 7.0/9.0/18.0), |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 583 | (g.expovariate, (1.5,), 1/1.5, 1/1.5**2), |
Serhiy Storchaka | 6c22b1d | 2013-02-10 19:28:56 +0200 | [diff] [blame] | 584 | (g.vonmisesvariate, (1.23, 0), pi, pi**2/3), |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 585 | (g.paretovariate, (5.0,), 5.0/(5.0-1), |
| 586 | 5.0/((5.0-1)**2*(5.0-2))), |
| 587 | (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0), |
| 588 | gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]: |
| 589 | g.random = x[:].pop |
| 590 | y = [] |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 591 | for i in range(len(x)): |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 592 | try: |
| 593 | y.append(variate(*args)) |
| 594 | except IndexError: |
| 595 | pass |
| 596 | s1 = s2 = 0 |
| 597 | for e in y: |
| 598 | s1 += e |
| 599 | s2 += (e - mu) ** 2 |
| 600 | N = len(y) |
Serhiy Storchaka | 6c22b1d | 2013-02-10 19:28:56 +0200 | [diff] [blame] | 601 | self.assertAlmostEqual(s1/N, mu, places=2, |
| 602 | msg='%s%r' % (variate.__name__, args)) |
| 603 | self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2, |
| 604 | msg='%s%r' % (variate.__name__, args)) |
| 605 | |
| 606 | def test_constant(self): |
| 607 | g = random.Random() |
| 608 | N = 100 |
| 609 | for variate, args, expected in [ |
| 610 | (g.uniform, (10.0, 10.0), 10.0), |
| 611 | (g.triangular, (10.0, 10.0), 10.0), |
Raymond Hettinger | 978c6ab | 2014-05-25 17:25:27 -0700 | [diff] [blame] | 612 | (g.triangular, (10.0, 10.0, 10.0), 10.0), |
Serhiy Storchaka | 6c22b1d | 2013-02-10 19:28:56 +0200 | [diff] [blame] | 613 | (g.expovariate, (float('inf'),), 0.0), |
| 614 | (g.vonmisesvariate, (3.0, float('inf')), 3.0), |
| 615 | (g.gauss, (10.0, 0.0), 10.0), |
| 616 | (g.lognormvariate, (0.0, 0.0), 1.0), |
| 617 | (g.lognormvariate, (-float('inf'), 0.0), 0.0), |
| 618 | (g.normalvariate, (10.0, 0.0), 10.0), |
| 619 | (g.paretovariate, (float('inf'),), 1.0), |
| 620 | (g.weibullvariate, (10.0, float('inf')), 10.0), |
| 621 | (g.weibullvariate, (0.0, 10.0), 0.0), |
| 622 | ]: |
| 623 | for i in range(N): |
| 624 | self.assertEqual(variate(*args), expected) |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 625 | |
Mark Dickinson | be5f919 | 2013-02-10 14:16:10 +0000 | [diff] [blame] | 626 | def test_von_mises_range(self): |
| 627 | # Issue 17149: von mises variates were not consistently in the |
| 628 | # range [0, 2*PI]. |
| 629 | g = random.Random() |
| 630 | N = 100 |
| 631 | for mu in 0.0, 0.1, 3.1, 6.2: |
| 632 | for kappa in 0.0, 2.3, 500.0: |
| 633 | for _ in range(N): |
| 634 | sample = g.vonmisesvariate(mu, kappa) |
| 635 | self.assertTrue( |
| 636 | 0 <= sample <= random.TWOPI, |
| 637 | msg=("vonmisesvariate({}, {}) produced a result {} out" |
| 638 | " of range [0, 2*pi]").format(mu, kappa, sample)) |
| 639 | |
Serhiy Storchaka | 6c22b1d | 2013-02-10 19:28:56 +0200 | [diff] [blame] | 640 | def test_von_mises_large_kappa(self): |
| 641 | # Issue #17141: vonmisesvariate() was hang for large kappas |
| 642 | random.vonmisesvariate(0, 1e15) |
| 643 | random.vonmisesvariate(0, 1e100) |
| 644 | |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 645 | def test_gammavariate_errors(self): |
| 646 | # Both alpha and beta must be > 0.0 |
| 647 | self.assertRaises(ValueError, random.gammavariate, -1, 3) |
| 648 | self.assertRaises(ValueError, random.gammavariate, 0, 2) |
| 649 | self.assertRaises(ValueError, random.gammavariate, 2, 0) |
| 650 | self.assertRaises(ValueError, random.gammavariate, 1, -3) |
| 651 | |
| 652 | @unittest.mock.patch('random.Random.random') |
| 653 | def test_gammavariate_full_code_coverage(self, random_mock): |
| 654 | # There are three different possibilities in the current implementation |
| 655 | # of random.gammavariate(), depending on the value of 'alpha'. What we |
| 656 | # are going to do here is to fix the values returned by random() to |
| 657 | # generate test cases that provide 100% line coverage of the method. |
| 658 | |
| 659 | # #1: alpha > 1.0: we want the first random number to be outside the |
| 660 | # [1e-7, .9999999] range, so that the continue statement executes |
| 661 | # once. The values of u1 and u2 will be 0.5 and 0.3, respectively. |
| 662 | random_mock.side_effect = [1e-8, 0.5, 0.3] |
| 663 | returned_value = random.gammavariate(1.1, 2.3) |
| 664 | self.assertAlmostEqual(returned_value, 2.53) |
| 665 | |
| 666 | # #2: alpha == 1: first random number less than 1e-7 to that the body |
| 667 | # of the while loop executes once. Then random.random() returns 0.45, |
| 668 | # which causes while to stop looping and the algorithm to terminate. |
| 669 | random_mock.side_effect = [1e-8, 0.45] |
| 670 | returned_value = random.gammavariate(1.0, 3.14) |
| 671 | self.assertAlmostEqual(returned_value, 2.507314166123803) |
| 672 | |
| 673 | # #3: 0 < alpha < 1. This is the most complex region of code to cover, |
| 674 | # as there are multiple if-else statements. Let's take a look at the |
| 675 | # source code, and determine the values that we need accordingly: |
| 676 | # |
| 677 | # while 1: |
| 678 | # u = random() |
| 679 | # b = (_e + alpha)/_e |
| 680 | # p = b*u |
| 681 | # if p <= 1.0: # <=== (A) |
| 682 | # x = p ** (1.0/alpha) |
| 683 | # else: # <=== (B) |
| 684 | # x = -_log((b-p)/alpha) |
| 685 | # u1 = random() |
| 686 | # if p > 1.0: # <=== (C) |
| 687 | # if u1 <= x ** (alpha - 1.0): # <=== (D) |
| 688 | # break |
| 689 | # elif u1 <= _exp(-x): # <=== (E) |
| 690 | # break |
| 691 | # return x * beta |
| 692 | # |
| 693 | # First, we want (A) to be True. For that we need that: |
| 694 | # b*random() <= 1.0 |
| 695 | # r1 = random() <= 1.0 / b |
| 696 | # |
| 697 | # We now get to the second if-else branch, and here, since p <= 1.0, |
| 698 | # (C) is False and we take the elif branch, (E). For it to be True, |
| 699 | # so that the break is executed, we need that: |
| 700 | # r2 = random() <= _exp(-x) |
| 701 | # r2 <= _exp(-(p ** (1.0/alpha))) |
| 702 | # r2 <= _exp(-((b*r1) ** (1.0/alpha))) |
| 703 | |
| 704 | _e = random._e |
| 705 | _exp = random._exp |
| 706 | _log = random._log |
| 707 | alpha = 0.35 |
| 708 | beta = 1.45 |
| 709 | b = (_e + alpha)/_e |
| 710 | epsilon = 0.01 |
| 711 | |
| 712 | r1 = 0.8859296441566 # 1.0 / b |
| 713 | r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha))) |
| 714 | |
| 715 | # These four "random" values result in the following trace: |
| 716 | # (A) True, (E) False --> [next iteration of while] |
| 717 | # (A) True, (E) True --> [while loop breaks] |
| 718 | random_mock.side_effect = [r1, r2 + epsilon, r1, r2] |
| 719 | returned_value = random.gammavariate(alpha, beta) |
| 720 | self.assertAlmostEqual(returned_value, 1.4499999999997544) |
| 721 | |
| 722 | # Let's now make (A) be False. If this is the case, when we get to the |
| 723 | # second if-else 'p' is greater than 1, so (C) evaluates to True. We |
| 724 | # now encounter a second if statement, (D), which in order to execute |
| 725 | # must satisfy the following condition: |
| 726 | # r2 <= x ** (alpha - 1.0) |
| 727 | # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0) |
| 728 | # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0) |
| 729 | r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False |
| 730 | r2 = 0.9445400408898141 |
| 731 | |
| 732 | # And these four values result in the following trace: |
| 733 | # (B) and (C) True, (D) False --> [next iteration of while] |
| 734 | # (B) and (C) True, (D) True [while loop breaks] |
| 735 | random_mock.side_effect = [r1, r2 + epsilon, r1, r2] |
| 736 | returned_value = random.gammavariate(alpha, beta) |
| 737 | self.assertAlmostEqual(returned_value, 1.5830349561760781) |
| 738 | |
| 739 | @unittest.mock.patch('random.Random.gammavariate') |
| 740 | def test_betavariate_return_zero(self, gammavariate_mock): |
| 741 | # betavariate() returns zero when the Gamma distribution |
| 742 | # that it uses internally returns this same value. |
| 743 | gammavariate_mock.return_value = 0.0 |
| 744 | self.assertEqual(0.0, random.betavariate(2.71828, 3.14159)) |
Serhiy Storchaka | 6c22b1d | 2013-02-10 19:28:56 +0200 | [diff] [blame] | 745 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 746 | class TestModule(unittest.TestCase): |
| 747 | def testMagicConstants(self): |
| 748 | self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141) |
| 749 | self.assertAlmostEqual(random.TWOPI, 6.28318530718) |
| 750 | self.assertAlmostEqual(random.LOG4, 1.38629436111989) |
| 751 | self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627) |
| 752 | |
| 753 | def test__all__(self): |
| 754 | # tests validity but not completeness of the __all__ list |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 755 | self.assertTrue(set(random.__all__) <= set(dir(random))) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 756 | |
Thomas Wouters | b213704 | 2007-02-01 18:02:27 +0000 | [diff] [blame] | 757 | def test_random_subclass_with_kwargs(self): |
| 758 | # SF bug #1486663 -- this used to erroneously raise a TypeError |
| 759 | class Subclass(random.Random): |
| 760 | def __init__(self, newarg=None): |
| 761 | random.Random.__init__(self) |
| 762 | Subclass(newarg=1) |
| 763 | |
| 764 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 765 | if __name__ == "__main__": |
Ezio Melotti | 3e4a98b | 2013-04-19 05:45:27 +0300 | [diff] [blame] | 766 | unittest.main() |