random 64-bit int

Jeff Davis jdavis at empires.org
Thu Jul 25 05:32:51 EDT 2002


Thank you for your reply (and the other person who responded).

You mention that I am wasting two random bytes. How might I go about 
getting those two bytes? if I use randrange() for the entire range of 
ints, than I get an overflow. random() isn't really all that random 
either, since it is only zero to one and a conversion to a float loses a 
lot of information (I think... let me know if I'm mistaken). The only 
thing I could think of was to use a short.

Thanks again,
        Jeff

Martin v. Loewis wrote:

> 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