[Tutor] What are these things urandom() returns?

Dick Moores rdm at rcblue.com
Tue Oct 10 22:15:38 CEST 2006


At 12:51 PM 10/10/2006, Tim Peters wrote:
>[Dick Moores]
>...
>>I'm thinking that just for the hell of it I could use urandom() as a
>>source of random decimal digits.
>
>You could, yes.
>
>>Or in a coin tossing program. Here's a list of 7817 '1's and 0's
>>generated by urandom():
>
>Note that the length of the list will vary from run to run.  Since you
>grab a million bytes, and there's a 1 in 128 chance of gettiing a 0 or
>1 byte, if  you run this code many times the /average/ length of the
>final list will be about 1000000./128 = 7812.5.

Yes, I saw that, thanks to Kent's earlier explanation.

>>  >>> from os import urandom
>>  >>> lst = list(urandom(1000000))
>>  >>> tosses = [y for y in lst if y in '01']
>>  >>> len(tosses)
>>7817
>>  >>>
>
>>Would this be a better random source than choice([0,1]), which uses random()?
>
>"Better" as measured against what criteria?

I meant would it be closer to true randomness than random(), even if 
much slower?

>  It's very much slower
>than using choice([0, 1])  (or choice("01"), or randrange(2), or ...),
>and can't (even in theory) be reproduced by setting a seed.

That's fine. Why would one want to?

>The only reason to use urandom() is if you /need/
>cryptographic-strength randomness.  For any meaning of "better" other
>than "cryptographically strong", no, urandom() isn't better.  If
>cryptographic strength is what you need, then urandom is not only
>better, there's no choice about it -- as the docs for random() say,
>the Mersenne Twister "completely unsuitable for cryptographic
>purposes".

No /need/, here. Just curiosity. I had enough of crypto in the Navy.

>Note that the random.SystemRandom class (see the docs) supplies the
>full range of convenience methods (like choice() and randrange()), but
>using urandom() as the base generator instead of the Mersenne Twister.

Great! I'll check them out.

Thanks very much, Tim.

Dick





More information about the Tutor mailing list