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