Truly random numbers

John La Rooy nospampls.jlr at doctor.com
Thu Feb 13 18:27:48 EST 2003


> Hi John,
> First of all, thanks a lot for your help. With your program I managed to solve the problem.
> But now I have another one:)
> With your program I get output in Hexadecimal form, which is good, but I would like a decimal output... The problem is that, when I change your format string in "%2.2d", the program won't even execute, actually it just stands and does nothing. And if I delete the format string the lenght of the group is higher than 4. The kind of output, and the program flow I'd like to see is something like this ( with of course random numbers ):
> 
> Enter the number of the groups: 7
> Your groups: [1111, 2222, 3333, 4444, 5555, 6666, 7777]
> 
> Sorry for my ignorance, but I don't know how to modify your program to output this kind of list...
> In case you forgot, here is how your source code looks like:
> 
> import select
> 
>     number_of_groups=10000
>     length_of_group=4
> 
>     dev_random=open("/dev/random")
>     P=select.poll()
>     P.register(dev_random.fileno(),select.POLLIN)
> 
>     groups=[]
> 
>     while len(groups) < number_of_groups:
>         group=""
>         while len(group) < length_of_group:
>             if P.poll(0.1):
>                 group+="%2.2X"%ord(dev_random.read(1))
>         groups.append(group)
>     print groups
> 
> Thanks again...
> Luka
> 

The program should still run if you change the X to a d. It may however
appear to be doing nothing if /dev/random is empty. It checks 10 times per
second to see if any new random numbers are there.

Your problem with the formatting is that each byte from /dev/random
represents a value from 0 to 255. This converts nicely to a 2 digit hex
number, but not so nicely to a decimal number. I suggest throwing away
numbers larger than 199 and then map 100->0, 101->1,... 199->99.

converting a 2 digit number to a 2 character string is no problem.
try these to see why the format string is %2.2d

print "%d"%11
print "%d"%2
print "%2d"%3
print "%2.2d"%4

which will give you something like this

        ...
        if P.poll(0.1):
            datum=ord(dev_random.read(1))
            if datum < 200:
                group+="%2.2d"%(datum%100)
        else:
            print "waiting for more data in /dev/random (moving the mouse or typing something helps)"
            print "got %d groups so far"%len(groups)
        ...


John




More information about the Python-list mailing list