random 64-bit int

Martin v. Loewis martin at v.loewis.de
Thu Jul 25 04:27:11 EDT 2002


Jeff Davis <jdavis at empires.org> writes:

> It seems like the above works, but I'd like to know whether I am losing 
> randomness, or whether there is a more efficient or faster way to 
> accomplish that. Would it be a good idea to include a call to 
> random.seed()?
> 
> Also, it would be *really* nice if there was a good way to do that in 
> python2.1, which does not seem to allow the "q" type for unpack().

I think the randomness of this is as good as any other algorithm you
could find. On speed and portability, you might consider using hex or
octal strings, or plain arithmetic computations. Notice that each
random() call really gives you roughly 32 bits of randomness, so you
are wasting 16 of them.

The approach based on octal numbers works on grounds of

long("-12312357623526234343454642342164",8)

being supported in all Python versions. Create 7 octal digits (21
bits, unsigned) with two call to random, then create the missing 22
bits (including sign) with another call; print the strings octal,
concatenate them, and invoke long().

The approach based on arithmetic works the same, but avoids the string
operations: Create three 21 bit numbers a, b, c (a should be signed),
then use
  long(a)<<42 + long(b)<<21 + c

You should time all three approaches if performance matters.

HTH,
Martin



More information about the Python-list mailing list