SHA-based subclass for Random module

Anton Vredegoor anton at vredegoor.doge.nl
Tue Mar 16 18:18:33 EST 2004


Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:

>http://www.nightsong.com/phr/python/sharandom.py
>
>This is intended to be less predicable/have fewer correlations than
>the default Mersenne Twister or Wichmann-Hill generators.  Comments
>are appreciated.

Nice idea, and thanks for SHAring, but I can't comment about its
predictability. What I know about MD5 or SHA is that these algorithms
try to dislocate bits as fast as possible per iteration. 

Consider the code below not as a tested random function but as an
exercise in floating point bit twiddling. (although it seems to work
reasonably well in a scatterplot) 

Anton

"""
I used this URL:

URL: http://www.psc.edu/general/software/packages/ieee/ieee.html 

more specific, this line:

S EEEEEEEEEEE FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF

and this :

If 0<E<2047 then V=(-1)**S * 2 ** (E-1023) * (1.F) where "1.F" is
intended to represent the binary number created by prefixing F with 
an implicit leading 1 and a binary point.

NOTE: if E==1023 then 2 ** (E-1023) == 2**0 == 1 so in the code
below I am setting S EEEEEEEEEEE to 0x3ff
"""

import md5, struct, time

s0,s1,offset = str(time.time()),'',14
def f(x):  return md5.new(x).digest()

def arand():
    global s0,s1,offset
    if offset >= 14: s0,s1,offset = f(s0),f(s0+s1),0
    b = chr(ord(s1[offset]) | 0xf0)
    c = s1[offset+1:offset+7]
    offset += 7
    return struct.unpack('>d','?'+b+c)[0]-1

def test(n=10000):
    return sum([arand() for i in xrange(n)])/n
    
if __name__=='__main__':
    print test()




More information about the Python-list mailing list