views:

102

answers:

1

I'm trying to model this problem (for details on it, http://www.mpi-hd.mpg.de/personalhomes/bauke/LABS/index.php)

I've seen that the proven minimum for a sequence of 10 digits is 13. However, my application seems to be getting 12 quite frequently. This implies some kind of error in my program. Is there an obvious error in the way I've modeled those summations in this code?

def evaluate(self):
    self.fitness = 10000000000 #horrible practice, I know..
    h = 0

    for g in range(1, len(self.chromosome) - 1):
        c = self.evaluateHelper(g)
        h += c**2
    self.fitness = h

def evaluateHelper(self, g):
    """
    Helper for evaluate function.  The c sub g function.
    """
    totalSum = 0
    for i in range(len(self.chromosome) - g - 1):
        product = self.chromosome[i] * self.chromosome[(i + g) % (len(self.chromosome))]
        totalSum += product
    return totalSum
+1  A: 

I can't spot any obvious bug offhand, but you're making things really complicated, so maybe a bug's lurking and hiding somewhere. What about

def evaluateHelper(self, g):
  return sum(a*b for a, b in zip(self.chromosome, self.chomosome[g:]))

this should return the same values you're computing in that subtle loop (where I think the % len... part is provably redundant). Similarly, the evaluate method seems ripe for a similar 1-liner. But, anyway...

There's a potential off-by-one issue: the formulas in the article you point to are summing for g from 1 to N-1 included -- you're using range(1, len(...)-1), whereby N-1 is excluded. Could that be the root of the problem you observe?

Alex Martelli
Sorry, maybe I've missed something but when I read the formulas, I'm still seeing g starting at 1? Also, thanks for the pointer on the zip function :)
Chris
@Chris, you're right -- the off-by-1 issue is different, let me edit the A accordingly.
Alex Martelli
Strange, the off-by-one thing was definitely a bug. I fixed it and still had the bug. I then replaced my summing loop with your sum statement and it seems to be fixed. I can't see how they're actually different, though. Strange. Thanks!
Chris
@Chris, I can't see the difference either -- but anyway, glad your bug is fixed, one way or another!-)
Alex Martelli