[Tutor] What are these things urandom() returns?
Tim Peters
tim.peters at gmail.com
Tue Oct 10 21:51:21 CEST 2006
[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.
> >>> 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? 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.
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".
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.
More information about the Tutor
mailing list