I'm playing around with genetic algorithms and I want to write a
function that mutates an integer by iterating across the bits, and about
1 in 10 times, it should switch a zero to a one, or a one to a zero.
I'm not sure how many bits are inside a python integer. The library
reference says at least 32.
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? 12 11754
Matthew Wilson <mw*****@sarcas tic-horse.com> writes: I'm playing around with genetic algorithms and I want to write a function that mutates an integer by iterating across the bits, and about 1 in 10 times, it should switch a zero to a one, or a one to a zero.
I'm not sure how many bits are inside a python integer. The library reference says at least 32.
Long ints can have as many bits as you want.
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?
Just shift and mask. Untested code:
def bit_stream(n):
p = 1
while p < n:
bit = (n & p) != 0
if rand() % 10 == 0:
bit = not bit
p = p * 2
yield bit
The above assumes you want to look at the bits sequentially, so it
doesn't try to change them inside the number, which would mean consing
up a new number every time a bit changes. If you want to look at them
all at once, your idea of making a list of bools and flipping a subset
of them is reasonable. An optimization for long ints would be use the
array module, convert your integer to an array, do a bunch of bit
flips in the array, and convert back.
> 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?
For speed, you should use shift and boolean ops - like this:
def mutate(seq, n=32, prob=0.05):
for bit in xrange(n):
if random.random() <= prob:
seq ^= 1 << bit
return seq
Regards,
Diez
Matthew> I'm playing around with genetic algorithms and I want to write
Matthew> a function that mutates an integer by iterating across the
Matthew> bits, and about 1 in 10 times, it should switch a zero to a
Matthew> one, or a one to a zero.
Just use Python's bitwise ops, for example: x = 0x0FFFCCCC hex(x)
'0xfffcccc' hex(x | (1 << 13))
'0xfffeccc'
Skip
Paul Rubin wrote: Matthew Wilson <mw*****@sarcas tic-horse.com> writes:
I'm playing around with genetic algorithms and I want to write a function that mutates an integer by iterating across the bits, and about 1 in 10 times, it should switch a zero to a one, or a one to a zero.
I'm not sure how many bits are inside a python integer. The library reference says at least 32.
Long ints can have as many bits as you want.
Such as -1L which has an infinite number of bits.
I have used a list of integers as my defacto standard for representing a
stream of bits. On my windows box this is slower than using a long
integer but with psyco running (psyco.sourcefo rge.net) it is faster than
the long integer implementation.
It also is faster to bail out on a comparison, for example
if (a&b)!= 0:
can be optimized to fail on the first integer failure, it doesn't have
to complete the operation as it would with a long integer.
This is useful when seeing if a bit string is contained inside another
bit string.
Matthew Wilson: I'm not sure how many bits are inside a python integer. The library reference says at least 32.
Platform dependent. Could be 64 on 64 bit machines.
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?
Python isn't good for that sort of low-level bit twiddling.
Here's another possibility. Use a long int as your genome,
then make a new long int which describes the bits which
need to be inverted, then apply an xor between them.
import random
def toLSBBinary(x, num_bits):
letters = []
for i in range(num_bits) :
if x & (1L << i):
letters.append( "1")
else:
letters.append( "0")
return "".join(letters )
genome = 3454579853467L
num_bits = 42
bitmask = 0
for i in range(num_bits) :
if random.random() < 0.1:
bitmask += 1L<<i
# genome bit, bitmask -> new value for genome
# if the bitmask is 0, don't change anything
# if it is 1, invert the value
# 0 0 -> 0
# 1 0 -> 1
# 0 1 -> 1
# 1 1 -> 0
# This is an xor
new_genome = (genome ^ bitmask)
print toLSBBinary(gen ome, num_bits)
print toLSBBinary(bit mask, num_bits)
print toLSBBinary(new _genome, num_bits)
Here's the output of the above
110110010001001 010000000101010 100010010011
100000101110100 000000000000000 000000010000
010110111111101 010000000101010 100010000011
Andrew da***@dalkescie ntific.com
Matthew Wilson <mw*****@sarcas tic-horse.com> wrote in message news:<sl******* *************@f rank.homelinux. net>... I'm playing around with genetic algorithms and I want to write a function that mutates an integer by iterating across the bits, and about 1 in 10 times, it should switch a zero to a one, or a one to a zero.
I'm not sure how many bits are inside a python integer. The library reference says at least 32.
It can vary from system to system, and is designed to accomodate
growth. Use sys.maxint to find out how large an integer is on your
system.
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. http://www.python.org/cgi-bin/moinmoin/BitwiseOperators
--
John J. Ladasky Jr., Ph.D.
Department of Biology
Johns Hopkins University
Baltimore MD 21218
USA
Earth
"Diez B. Roggisch" <de************ @web.de> wrote in message
news:bn******** *****@news.t-online.com... 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?
For speed, you should use shift and boolean ops - like this:
def mutate(seq, n=32, prob=0.05): for bit in xrange(n): if random.random() <= prob: seq ^= 1 << bit return seq
Regards,
Diez
And you might want to make a list of precalculated masks using the shift
operator for even more speed.
#! /usr/bin/env python
import sys
print sys.maxint
i = sys.maxint
bitcount = 0
while (i != 0):
i >>= 1
bitcount += 1
print "i = %d" % (i)
print "bitcount = %d" % (bitcount)
masklist = []
for i in range(bitcount) :
masklist.append (1 << i)
masklist.append (sys.maxint + 1)
for i in masklist:
print hex(i)
thelist = [0x7F, 0x5A5A5A5A]
for i in thelist:
for mask in masklist:
if ((i & mask) <> 0):
# do True thing
print "True"
else:
# do False thing
print "False"
Matthew Wilson wrote: I'm playing around with genetic algorithms and I want to write a function that mutates an integer by iterating across the bits, and about 1 in 10 times, it should switch a zero to a one, or a one to a zero.
I'm not sure how many bits are inside a python integer. The library reference says at least 32.
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?
You may be interested in the 'intbv' class that is part of my 'myhdl'
package for hardware design (link: see signature).
An intbv behaves like a Python long with an indefinite number of bits.
However, it is a mutable type that can also be used as a bitvector
through an indexing and slicing interface. Warning: slicing ranges are
downward as is common in hardware design but uncommon in Python.
Demo: from myhdl import intbv n = intbv(0xDE) n[:8] = 0xFA hex(n)
'0xFADEL' n[8:] = 0xB4 hex(n)
'0xFAB4L' for bit in n[12:8]:
.... print bit
....
1
0
1
0 n[123]
intbv(0L) n[123] = 1 hex(n)
'0x800000000000 000000000000000 FAB4L'
Regards, Jan
--
Jan Decaluwe - Resources bvba - http://jandecaluwe.com
Losbergenlaan 16, B-3010 Leuven, Belgium
Bored with EDA the way it is? Check this: http://jandecaluwe.com/Tools/MyHDL/Overview.html la*****@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 "Probabilit y of the number of bits set:\n"
for i,c in enumerate(chanc es):
print "%i: %e" %(i,c)
if __name__=='__ma in__':
test() This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Patrick von Harsdorf |
last post by:
I want to iterate over a collection and delete all unwanted entries.
for item in collection:
del item
of course doesn´t do anything useful. Two things come to mind:
a) iterating backwards over the collection using indexing, something like:
for i in range(len(collection)-1, -1, -1):
item = collection
|
by: Fernando Rodríguez |
last post by:
Hi,
While iterating through a list I'd like to know not just the current element,
but also its index. Is there a better way than this:
i = 0
newList =
for element in aList:
newList.append((i, element))
i += 1
|
by: ischenko |
last post by:
Hi,
I'm trying to find all modules that contain doctests and execute them
(using DocTestSuite). The problem is how to iterate (programmatically)
through the package's modules.
>>> import M
>>> inspect.getmembers(M, inspect.ismodule)
|
by: Paxton |
last post by:
At the risk of being told "If it ain't broke, don't fix it", my code works,
but is ugly.
Part of the admin site I'm working on at the moment includes a facility for
users to enter Formulations (recipes for making cosmetics etc) in 3 stages:
Stage 1: basic info such as title, method etc and number of Phases (steps in
recipe).
Stage 2: dynamically generated form containing the exact number of phases as
textboxes, depending on the number...
|
by: jose luis fernandez diaz |
last post by:
Hi,
Is this right any stl container (vector, deque, list, . . .)?
typedef vector container;
int main()
{
container<int> c1;
| |
by: Dave Hansen |
last post by:
OK, first, I don't often have the time to read this group, so
apologies if this is a FAQ, though I couldn't find anything at
python.org.
Second, this isn't my code. I wouldn't do this. But a colleague did,
got an unexpected result, and asked me why. I think I can infer what
is occurring, and I was able to find a simple work-around. But I
thought I'd ask about it anyway.
I've been pushing Python at work for use as a scripting...
|
by: Gustaf Liljegren |
last post by:
I ran into this problem today: I got an array with Account objects. I need
to iterate through this array to supplement the accounts in the array with
more data. But the compiler complains when I try to modify the objects in
the array while iterating through it. I marked the bugs in this code:
// Loop through all previously added accounts
foreach(Account a in a1) // a1 is an ArrayList
{
// If name and context is the same
if(a.Name ==...
|
by: Nick |
last post by:
Hi all,
Just a quick question. I have a class that exposes a number of fields (which
are themselves custom types) through public properties.
At run time, I have an object whom I'd like to check, is of same type as one
of these fields.
Is there a method or technique for iterating through a class's public
properties, such as maybe using something from the reflection namespace?
|
by: Alan |
last post by:
I was wondering whether it is good programming practice or asking
for trouble to modify a vector while iterating through it. That is, I
want to do something like the following pseudocode in C++:
for each element of the vector
for each subsequent element of the vector
if the belong together <some code to compare them>
then merge the elements (add the 2nd to the 1st, then
delete the 1st)
|
by: SBMpy |
last post by:
Instead of itereating through my half-million plus records, I'm looking for a way to query the records and return a subset of records.
Q: Does dbfpy have that functionality?
Q: Or is there a means of performing a query that returns a subset of records without iterating over every record?
Currently I load all the records into an array:
for rec2 in db2:
rList.append(rec2)
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |