blob: 970b8620bad4463ee873771d4cb8de7d4a3bd6a3 [file] [log] [blame]
Raymond Hettinger40f62172002-12-29 23:03:38 +00001#!/usr/bin/env python
2
3import unittest
Tim Peters46c04e12002-05-05 20:40:00 +00004import random
Raymond Hettinger40f62172002-12-29 23:03:38 +00005import time
Raymond Hettinger3dd990c2003-01-05 09:20:06 +00006from math import log, exp, sqrt, pi
Raymond Hettinger7b0cf762003-01-17 17:23:23 +00007from sets import Set
Raymond Hettinger40f62172002-12-29 23:03:38 +00008from test import test_support
Tim Peters46c04e12002-05-05 20:40:00 +00009
Raymond Hettinger40f62172002-12-29 23:03:38 +000010class TestBasicOps(unittest.TestCase):
11 # Superclass with tests common to all generators.
12 # Subclasses must arrange for self.gen to retrieve the Random instance
13 # to be tested.
Tim Peters46c04e12002-05-05 20:40:00 +000014
Raymond Hettinger40f62172002-12-29 23:03:38 +000015 def randomlist(self, n):
16 """Helper function to make a list of random numbers"""
17 return [self.gen.random() for i in xrange(n)]
Tim Peters46c04e12002-05-05 20:40:00 +000018
Raymond Hettinger40f62172002-12-29 23:03:38 +000019 def test_autoseed(self):
20 self.gen.seed()
21 state1 = self.gen.getstate()
Raymond Hettinger785d0a32003-02-21 01:41:36 +000022 time.sleep(1.1)
Raymond Hettinger40f62172002-12-29 23:03:38 +000023 self.gen.seed() # diffent seeds at different times
24 state2 = self.gen.getstate()
25 self.assertNotEqual(state1, state2)
Tim Peters46c04e12002-05-05 20:40:00 +000026
Raymond Hettinger40f62172002-12-29 23:03:38 +000027 def test_saverestore(self):
28 N = 1000
29 self.gen.seed()
30 state = self.gen.getstate()
31 randseq = self.randomlist(N)
32 self.gen.setstate(state) # should regenerate the same sequence
33 self.assertEqual(randseq, self.randomlist(N))
34
35 def test_seedargs(self):
36 for arg in [None, 0, 0L, 1, 1L, -1, -1L, 10**20, -(10**20),
37 3.14, 1+2j, 'a', tuple('abc')]:
38 self.gen.seed(arg)
39 for arg in [range(3), dict(one=1)]:
40 self.assertRaises(TypeError, self.gen.seed, arg)
41
42 def test_jumpahead(self):
43 self.gen.seed()
44 state1 = self.gen.getstate()
45 self.gen.jumpahead(100)
46 state2 = self.gen.getstate() # s/b distinct from state1
47 self.assertNotEqual(state1, state2)
48 self.gen.jumpahead(100)
49 state3 = self.gen.getstate() # s/b distinct from state2
50 self.assertNotEqual(state2, state3)
51
52 self.assertRaises(TypeError, self.gen.jumpahead) # needs an arg
53 self.assertRaises(TypeError, self.gen.jumpahead, "ick") # wrong type
54 self.assertRaises(TypeError, self.gen.jumpahead, 2.3) # wrong type
55 self.assertRaises(TypeError, self.gen.jumpahead, 2, 3) # too many
56
57 def test_sample(self):
58 # For the entire allowable range of 0 <= k <= N, validate that
59 # the sample is of the correct length and contains only unique items
60 N = 100
61 population = xrange(N)
62 for k in xrange(N+1):
63 s = self.gen.sample(population, k)
64 self.assertEqual(len(s), k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +000065 uniq = Set(s)
Raymond Hettinger40f62172002-12-29 23:03:38 +000066 self.assertEqual(len(uniq), k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +000067 self.failUnless(uniq <= Set(population))
Raymond Hettinger8ec78812003-01-04 05:55:11 +000068 self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
Raymond Hettinger40f62172002-12-29 23:03:38 +000069
Raymond Hettinger7b0cf762003-01-17 17:23:23 +000070 def test_sample_distribution(self):
71 # For the entire allowable range of 0 <= k <= N, validate that
72 # sample generates all possible permutations
73 n = 5
74 pop = range(n)
75 trials = 10000 # large num prevents false negatives without slowing normal case
76 def factorial(n):
Raymond Hettinger105b0842003-02-04 05:47:30 +000077 return reduce(int.__mul__, xrange(1, n), 1)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +000078 for k in xrange(n):
79 expected = factorial(n) / factorial(n-k)
80 perms = {}
81 for i in xrange(trials):
82 perms[tuple(self.gen.sample(pop, k))] = None
83 if len(perms) == expected:
84 break
85 else:
86 self.fail()
87
Raymond Hettinger40f62172002-12-29 23:03:38 +000088 def test_gauss(self):
89 # Ensure that the seed() method initializes all the hidden state. In
90 # particular, through 2.2.1 it failed to reset a piece of state used
91 # by (and only by) the .gauss() method.
92
93 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
94 self.gen.seed(seed)
95 x1 = self.gen.random()
96 y1 = self.gen.gauss(0, 1)
97
98 self.gen.seed(seed)
99 x2 = self.gen.random()
100 y2 = self.gen.gauss(0, 1)
101
102 self.assertEqual(x1, x2)
103 self.assertEqual(y1, y2)
104
105
106class WichmannHill_TestBasicOps(TestBasicOps):
107 gen = random.WichmannHill()
108
109 def test_strong_jumpahead(self):
110 # tests that jumpahead(n) semantics correspond to n calls to random()
111 N = 1000
112 s = self.gen.getstate()
113 self.gen.jumpahead(N)
114 r1 = self.gen.random()
115 # now do it the slow way
116 self.gen.setstate(s)
117 for i in xrange(N):
118 self.gen.random()
119 r2 = self.gen.random()
120 self.assertEqual(r1, r2)
121
122 def test_gauss_with_whseed(self):
123 # Ensure that the seed() method initializes all the hidden state. In
124 # particular, through 2.2.1 it failed to reset a piece of state used
125 # by (and only by) the .gauss() method.
126
127 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
128 self.gen.whseed(seed)
129 x1 = self.gen.random()
130 y1 = self.gen.gauss(0, 1)
131
132 self.gen.whseed(seed)
133 x2 = self.gen.random()
134 y2 = self.gen.gauss(0, 1)
135
136 self.assertEqual(x1, x2)
137 self.assertEqual(y1, y2)
138
139class MersenneTwister_TestBasicOps(TestBasicOps):
140 gen = random.Random()
141
142 def test_referenceImplementation(self):
143 # Compare the python implementation with results from the original
144 # code. Create 2000 53-bit precision random floats. Compare only
145 # the last ten entries to show that the independent implementations
146 # are tracking. Here is the main() function needed to create the
147 # list of expected random numbers:
148 # void main(void){
149 # int i;
150 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
151 # init_by_array(init, length);
152 # for (i=0; i<2000; i++) {
153 # printf("%.15f ", genrand_res53());
154 # if (i%5==4) printf("\n");
155 # }
156 # }
157 expected = [0.45839803073713259,
158 0.86057815201978782,
159 0.92848331726782152,
160 0.35932681119782461,
161 0.081823493762449573,
162 0.14332226470169329,
163 0.084297823823520024,
164 0.53814864671831453,
165 0.089215024911993401,
166 0.78486196105372907]
167
168 self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96))
169 actual = self.randomlist(2000)[-10:]
170 for a, e in zip(actual, expected):
171 self.assertAlmostEqual(a,e,places=14)
172
173 def test_strong_reference_implementation(self):
174 # Like test_referenceImplementation, but checks for exact bit-level
175 # equality. This should pass on any box where C double contains
176 # at least 53 bits of precision (the underlying algorithm suffers
177 # no rounding errors -- all results are exact).
178 from math import ldexp
179
180 expected = [0x0eab3258d2231fL,
181 0x1b89db315277a5L,
182 0x1db622a5518016L,
183 0x0b7f9af0d575bfL,
184 0x029e4c4db82240L,
185 0x04961892f5d673L,
186 0x02b291598e4589L,
187 0x11388382c15694L,
188 0x02dad977c9e1feL,
189 0x191d96d4d334c6L]
190
191 self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96))
192 actual = self.randomlist(2000)[-10:]
193 for a, e in zip(actual, expected):
194 self.assertEqual(long(ldexp(a, 53)), e)
195
196 def test_long_seed(self):
197 # This is most interesting to run in debug mode, just to make sure
198 # nothing blows up. Under the covers, a dynamically resized array
199 # is allocated, consuming space proportional to the number of bits
200 # in the seed. Unfortunately, that's a quadratic-time algorithm,
201 # so don't make this horribly big.
202 seed = (1L << (10000 * 8)) - 1 # about 10K bytes
203 self.gen.seed(seed)
204
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000205_gammacoeff = (0.9999999999995183, 676.5203681218835, -1259.139216722289,
206 771.3234287757674, -176.6150291498386, 12.50734324009056,
207 -0.1385710331296526, 0.9934937113930748e-05, 0.1659470187408462e-06)
208
209def gamma(z, cof=_gammacoeff, g=7):
210 z -= 1.0
211 sum = cof[0]
212 for i in xrange(1,len(cof)):
213 sum += cof[i] / (z+i)
214 z += 0.5
215 return (z+g)**z / exp(z+g) * sqrt(2*pi) * sum
216
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000217class TestDistributions(unittest.TestCase):
218 def test_zeroinputs(self):
219 # Verify that distributions can handle a series of zero inputs'
220 g = random.Random()
221 x = [g.random() for i in xrange(50)] + [0.0]*5
222 g.random = x[:].pop; g.uniform(1,10)
223 g.random = x[:].pop; g.paretovariate(1.0)
224 g.random = x[:].pop; g.expovariate(1.0)
225 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
226 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
227 g.random = x[:].pop; g.gauss(0.0, 1.0)
228 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
229 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
230 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
231 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
232 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
233 g.random = x[:].pop; g.betavariate(3.0, 3.0)
234
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000235 def test_avg_std(self):
236 # Use integration to test distribution average and standard deviation.
237 # Only works for distributions which do not consume variates in pairs
238 g = random.Random()
239 N = 5000
240 x = [i/float(N) for i in xrange(1,N)]
241 for variate, args, mu, sigmasqrd in [
242 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
243 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
244 (g.paretovariate, (5.0,), 5.0/(5.0-1),
245 5.0/((5.0-1)**2*(5.0-2))),
246 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
247 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
248 g.random = x[:].pop
249 y = []
250 for i in xrange(len(x)):
251 try:
252 y.append(variate(*args))
253 except IndexError:
254 pass
255 s1 = s2 = 0
256 for e in y:
257 s1 += e
258 s2 += (e - mu) ** 2
259 N = len(y)
260 self.assertAlmostEqual(s1/N, mu, 2)
261 self.assertAlmostEqual(s2/(N-1), sigmasqrd, 2)
262
Raymond Hettinger40f62172002-12-29 23:03:38 +0000263class TestModule(unittest.TestCase):
264 def testMagicConstants(self):
265 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
266 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
267 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
268 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
269
270 def test__all__(self):
271 # tests validity but not completeness of the __all__ list
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000272 self.failUnless(Set(random.__all__) <= Set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000273
Raymond Hettinger105b0842003-02-04 05:47:30 +0000274def test_main(verbose=None):
Raymond Hettinger27922ee2003-05-03 03:38:01 +0000275 testclasses = (WichmannHill_TestBasicOps,
Raymond Hettinger40f62172002-12-29 23:03:38 +0000276 MersenneTwister_TestBasicOps,
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000277 TestDistributions,
Raymond Hettinger27922ee2003-05-03 03:38:01 +0000278 TestModule)
279 test_support.run_unittest(*testclasses)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000280
Raymond Hettinger105b0842003-02-04 05:47:30 +0000281 # verify reference counting
282 import sys
283 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger320a1b02003-05-02 22:44:59 +0000284 counts = [None] * 5
285 for i in xrange(len(counts)):
Raymond Hettinger27922ee2003-05-03 03:38:01 +0000286 test_support.run_unittest(*testclasses)
Raymond Hettinger320a1b02003-05-02 22:44:59 +0000287 counts[i] = sys.gettotalrefcount()
Raymond Hettinger105b0842003-02-04 05:47:30 +0000288 print counts
289
Raymond Hettinger40f62172002-12-29 23:03:38 +0000290if __name__ == "__main__":
Raymond Hettinger105b0842003-02-04 05:47:30 +0000291 test_main(verbose=True)