33import unittest
44import random
55import time
6+ from math import log , exp , sqrt , pi
67from test import test_support
78
89class TestBasicOps (unittest .TestCase ):
@@ -182,6 +183,18 @@ def test_long_seed(self):
182183 seed = (1L << (10000 * 8 )) - 1 # about 10K bytes
183184 self .gen .seed (seed )
184185
186+ _gammacoeff = (0.9999999999995183 , 676.5203681218835 , - 1259.139216722289 ,
187+ 771.3234287757674 , - 176.6150291498386 , 12.50734324009056 ,
188+ - 0.1385710331296526 , 0.9934937113930748e-05 , 0.1659470187408462e-06 )
189+
190+ def 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+
185198class TestDistributions (unittest .TestCase ):
186199 def test_zeroinputs (self ):
187200 # Verify that distributions can handle a series of zero inputs'
@@ -200,6 +213,34 @@ def test_zeroinputs(self):
200213 g .random = x [:].pop ; g .gammavariate (200.0 , 1.0 )
201214 g .random = x [:].pop ; g .betavariate (3.0 , 3.0 )
202215
216+ 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+
203244class TestModule (unittest .TestCase ):
204245 def testMagicConstants (self ):
205246 self .assertAlmostEqual (random .NV_MAGICCONST , 1.71552776992141 )
0 commit comments