SHA-based subclass for random module
Anton Vredegoor
anton at vredegoor.doge.nl
Sat Mar 20 20:28:14 EST 2004
python at rcn.com (Raymond Hettinger) wrote:
>from random import Random
>from struct import unpack
>import md5
>
>class MD5Random(Random):
> def random(self, tofloat = 1.0 / 2 ** 53):
> plaintxt = str(Random.getrandbits(self, 128))
> ciphertxt = md5.new(plaintxt).digest()
> randint = unpack('<Q', ciphertxt[:8])[0] >> 11 # grab 53 bits
> return randint * tofloat
I wonder why it is necessary to do the bit twiddling once one has
chosen to multiply by a fraction instead of directly putting the bits
inside a float. If 1.0 / 2**53 is just some arbitrary value (and why
not: A floats' smallest value is a lot smaller than that?) then we can
generate integers of other sizes and divide them by other floats, for
example:
from random import Random
import md5
class MD5Random(Random):
def random(self, tofloat = 1.0/2**128, prf = md5.new()):
prf.update(repr(Random.random(self)))
return int(prf.hexdigest(),16) * tofloat
def test():
random = MD5Random().random
for i in range(10):
print random()
if __name__=='__main__':
test()
Anton
More information about the Python-list
mailing list