1
2
3
4
5
6 """handles true random numbers supplied from the the web server of fourmilab. Based on atmospheric noise. The motivation is to support biosimulations that rely on random numbers.
7 """
8
9 import string
10 import urllib
11
12
14 num_val = 0L
15 text = text.lower()
16 for letter in text:
17 hex_digit = string.hexdigits.find( letter )
18 if( hex_digit < 0 ):
19 raise ValueError
20 num_val = ( num_val * 16 ) + hex_digit
21 return num_val
22
24 val = 0
25 numbytes = len( text )
26 for i in range( 0, numbytes ):
27 val = val * 256
28 val = val + ord( text[ i ] )
29
30 return val
31
33
35
36 self.url = 'http://www.random.org/cgi-bin/randbyte?'
37 self.query = { 'nbytes' : 128, 'fmt' : 'h' }
38 self.fill_hot_cache()
39
41 url = self.url + urllib.urlencode( self.query )
42 fh = urllib.urlopen( url )
43 self.hot_cache = fh.read()
44 fh.close()
45
47 cache = self.hot_cache
48 numbytes = num_digits / 2
49 if( len( cache ) % numbytes != 0 ):
50 print 'len_cache is %d' % len( cache )
51 raise ValueError
52 if( cache == '' ):
53 self.fill_hot_cache()
54 cache = self.hot_cache
55 hexdigits = cache[ :numbytes ]
56 self.hot_cache = cache[ numbytes: ]
57 return byte_concat( hexdigits )
58
59
60
62
65
67 span = high - low
68 val = self.hot_cache.next_num()
69 val = ( span * val ) >> 16
70 val = val + low
71 return val
72
73
74 if( __name__ == '__main__' ):
75 hot_random = HotRandom()
76 for j in range ( 0, 130 ):
77 print hot_random.hot_rand( 25 )
78 nums = [ '0000', 'abcd', '1234', '5555', '4321', 'aaaa', 'ffff' ]
79 for num in nums:
80 print hex_convert( num )
81