Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random.shuffle Randomness

I am trying to write a genetic algorithm for homework to solve the travelling salesman problem.

One of the mutation functions that I'm trying is to use random.shuffle on the tour.

When I read the documentation for random.shuffle, I see:

shuffle(self, x, random=None, int=<type 'int'>) method of random.Random instance
x, random=random.random -> shuffle list x in place; return None.

Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random.

Could someone please explain the function of the "random" parameter in this function? I have read this question, but it doesn't answer my question.

I would especially like to use this function if I can somehow control how random the shuffling would be (if that makes any sense)

like image 947
inspectorG4dget Avatar asked Jan 31 '12 00:01

inspectorG4dget


1 Answers

The random argument is used for specifying (another) random number generator. it's a function expected to return uniform random numbers in the range 0<=x<1

If the same number is returned twice from the random number generator, the shuffle will be the same. For example,

def mynonrandom():
 return 0.1

q
[1, 2, 3, 4]
random.shuffle(q, mynonrandom)
q
[2, 3, 4, 1]
random.shuffle(q, mynonrandom)
q
[3, 4, 1, 2]

note that in this particular case I got a shift of -1 each time. Exactly what you get for a random input may depend on the implementation of random.shuffle.

For a genetic algorithm you want to be able to have variable sized randomness of the shuffle. That is not done with random.shuffle. You probably need to define some example changes (pairs with distance N swapping for example) and then randomize (with some parameters you'll define) how many of those operations you perform for each new set of genes.

like image 72
Johan Lundberg Avatar answered Oct 11 '22 15:10

Johan Lundberg