Main Content

Reproduce Results

Because the genetic algorithm is stochastic—that is, it makes random choices—you get slightly different results each time you run the genetic algorithm. The algorithm uses the default MATLAB® pseudorandom number stream. For more information about random number streams, see RandStream. Each time ga calls the stream, its state changes. So that the next time ga calls the stream, it returns a different random number. This is why the output of ga differs each time you run it.

If you need to reproduce your results exactly, you can call ga with an output argument that contains the current state of the default stream, and then reset the state to this value before running ga again. For example, to reproduce the output of ga applied to Rastrigin's function, call ga with the syntax

rng(1,'twister') % for reproducibility
% Define Rastrigin's function
rastriginsfcn = @(pop)10.0 * size(pop,2) + sum(pop .^2 - 10.0*cos(2*pi.*pop),2);
[x,fval,exitflag,output] = ga(rastriginsfcn, 2);

Suppose the results are

x,fval,exitflag
x =
   -1.0421   -1.0018

fval =
    2.4385

exitflag =
     1

The state of the stream is stored in output.rngstate. To reset the state, enter

stream = RandStream.getGlobalStream;
stream.State = output.rngstate.State;

If you now run ga a second time, you get the same results as before:

[x,fval,exitflag] = ga(rastriginsfcn, 2)
Optimization terminated: average change in the fitness value less than options.FunctionTolerance.

x =
   -1.0421   -1.0018

fval =
    2.4385

exitflag =
     1

Note

If you do not need to reproduce your results, it is better not to set the state of the stream, so that you get the benefit of the randomness in the genetic algorithm.

Related Topics