while loop unexpected behaviour (at least for me :) )

Hi All,

I am learning Julia by implementing code from the book of ‘Genetic Algorithm in python’. Because I also want to learn more GA. This refers to finding magic squares via GA in Simulated Annealing(chapter 8).

I have notice a certain type of behavior which I can’t explain but happens. I think it is specific to the while loop but I could be wrong.

The initial parent is made and then it calculates the fitness. Age at this point is 0. The function ‘taking_sample’ swaps to values in the parent and this becomes the child, the child’s fitness is tested against the existing parent. If it is better (lower is better). Then it is taken as parent and the whole process is started over again.

What I expect is that the swap is made, fitness calculated and if this is not better (or equal) it reverts back to the initial parent and does a new swap.

What actually happens is that it makes the swap from the original parent and then keeps swapping from the child. So it does not revert back to the parent and to start a new swap.

Can someone explain why this behavior is happening? Is it a logical mistake I am making?

I know that the while loop counter needs to be a global variable but i can’t s

Any feedback is welcome!

Best,

Alexander Chen

function main_loop(number)

  parent = generate_matrix(number)
  parent_fitness = first(summing(parent))
  constant = magic_constant(number)

  age = 0

  while parent_fitness != 0

    child = taking_sample(parent)
    child_fitness = first(summing(child))

    age += 1

      if abs(child_fitness) <= abs(parent_fitness)
        println("fitness dropped to $(child_fitness), age was: $(age)")
        parent = copy(child)
        parent_fitness = first(summing(parent))
        age = 0
        display(parent)
      else
        continue
      end
  end
  println("this is the correct lay-out with a magic constant of $(constant)")
  return parent
end

Welcome!

I’m afraid that it’s going to be very hard to answer your question from the information you’ve given. In particular, your example relies on a bunch of functions that we don’t have access to, and there’s probably a lot of complexity here that isn’t relevant to the problem. If you can remove all the extra complexity and boil the problem down to one thing, you’ll be much more likely to get a useful answer. For more info, please take a look at Please read: make it easier to help you

3 Likes

Hi rdeits,

I understand. I will try and strip it down as far as i can.

thanks,