我自己的Python RNG的随机性测试

时间:2014-10-22 08:03:44

标签: python random scipy

这是对我的特殊任务,我无法理解,我感到困惑。 我有以下随机数生成器类。

rng.py

#!/usr/bin/env python

class rngA():   
    def __init__(self, seed=0): self.state = seed
    def setSeed(self, seed): self.state = seed
    def rand(self): return 1.0*self.next()/(1<<32)
    def current(self): return self.state    
    def next(self):
        self.state = (69069 * self.state + 12345) & 0xFFFFFFFF
        return self.state

class rngB():   
    def __init__(self, seed=1): self.state = seed
    def setSeed(self, seed): self.state = seed
    def rand(self): return 1.0*self.next()/(1<<31)
    def current(self): return self.state    
    def next(self):
        self.state = (65539 * self.state + 4294967296) & 0x7FFFFFFF
        return self.state

class rngC():   
    def __init__(self, seed=1): self.state = seed
    def setSeed(self, seed): self.state = seed
    def rand(self): return 1.0*self.next()/(1<<12)
    def current(self): return self.state    
    def next(self):
        self.state = ((((16339 * self.state>>4 + 1) & 0xFF) + 4294967296) & 0x7FFFFFFF)<<4
        return self.state

class rngD():   
    def __init__(self, seed=1): 
        self.state = self.store = seed
    def setSeed(self, seed): self.state = seed
    def rand(self): return 1.0*self.next()/(1<<32)
    def current(self): return self.state    
    def next(self):
        self.store = self.state
        self.state = (69069 * self.state + 12345) & 0xFFFFFFFF
        self.state = int(.8*self.state+0.2*self.store)
        return self.state

class rngE():   
    def __init__(self, seed=12345): self.state = seed
    def setSeed(self, seed): self.state = seed
    def rand(self): return 1.0*self.next()/(1<<31)
    def current(self): return self.state    
    def next(self):
        self.state = (397204094 * self.state ) & 0x7FFFFFFF
        return self.state

如何测试RNG的随机性。

有一些测试,如

1.Frequency test
2.Runs test
3.Autocorrelation test
4.Gap test
5.Poker test

但我无法理解如何使用python执行此操作。请帮我解决一下我可以完成任务的方法。

谢谢

1 个答案:

答案 0 :(得分:1)

这样一个简单的例子:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

def test_function():

    test_times = 10000

    a_object = rngA()
    b_object = rngB()
    c_object = rngC()
    d_object = rngD()

    a_res = []
    b_res = []
    c_res = []
    d_res = []

    for i in xrange(test_times):
        a_res.append(a_object.rand)
        b_res.append(b_object.rand)
        c_res.append(c_object.rand)
        d_res.append(d_object.rand)

    test_res = a_res + b_res + c_res + d_res

    if len(set(test_res)) != test_times*4:
        print 'test fails, there is recepition!!'
    else:
        print 'test passes, they are all random!!'