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