[Tutor] What are these things urandom() returns?
Alan Gauld
alan.gauld at btinternet.com
Wed Oct 11 00:13:19 CEST 2006
> I'm thinking that just for the hell of it I could use urandom() as a
> source of random decimal digits. Or in a coin tossing program.
> Here's
> a list of 7817 '1's and 0's generated by urandom():
>
> >>> 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()?
It depends on what you mean by better.
Its not really any more random if thats what you mean,
it might be faster but I doubt if by much. I assume that
choice simply divides random by the number of options
and selects by index. In pseudo code:
def choice(seq):
ran = random() # number between 0,1
num = 1/len(seq) # 4 numbers means quarter interval?
for n in range(1,len(seq)+1):
if ran < num * n: break
return seq[n-1]
That probably has some boundary errors but I'd guess its how it works,
and if written in C is probably faster than generating a big list then
extracting the 1s and zeros into another list.
But in matters of timing its better to test than guess... :-)
Alan G.
More information about the Tutor
mailing list