iterating bit-by-bit across int?

Anton Vredegoor anton at vredegoor.doge.nl
Fri Oct 24 07:05:50 EDT 2003


ladasky at my-deja.com (John Ladasky) wrote:

>> I'm thinking about writing a function that eats integers and poops out
>> lists of bools; and then I can iterate through that, and change values
>> in there.  But before I do that, does anyone have a better idea?
>
>Using your approach, you would first need to disassemble the integer,
>then reassemble it.  You can cut this bitwise cranking in half. 
>Define an integer, in which 10% of the bits is a "1".  Then do an
>exclusive-or operation between this integer and the one you wish to
>mutate.

This creates a new problem which is interesting in itself. How to
create this integer? One idea is to first choose *how many* bits are
"1" and next randomly choose from one of the possible placements of
these bits inside an integer. Below I'm computing the probability
distribution for the number of bits that are set. 

Anton

def noverk(n, k):
    result = 1l
    for i in range(k):
        result = result *(n - i) / (i + 1)
    return result

def test():
    prob = 1/10.0
    n_bits = 32
    chances = [0.0 for i in range(n_bits+1)]
    for i in range(n_bits+1):
        a = noverk(n_bits,i)
        chances[i] = a*(prob**i)*(1-prob)**(n_bits-i)
    print "Probability of the number of bits set:\n"
    for i,c in enumerate(chances): 
        print "%i: %e" %(i,c)
    
if __name__=='__main__':
    test()




More information about the Python-list mailing list