/* Tutorial 03 Simplest EA (simpleEA.c) // Victor Landassuri-Moreno // School of Computer Science // University of Birmingham // Oct-2008 // function to optimize : x*x // population size 10 // size of the genotype --> 11 bits // this algorithm only consider positive numbers // this code is only for teaching purpose and must be // use in the same way!! // compile as: cc simpleEA.c -o simpleEA // alternate if troubles: cc simpleEA.c -O -lm -o simpleEA // run: ./simpleEA (depends of the linux version) */ #include #include #include #include //global variables///////// int population = 10; int size_ind = 11; int toSelect = 10; //parents to select int maxGen = 1000; int band = 0; //change to 1 if you want to show all message in screen //population char Population[10][11]; //the actual population char Offspring[10][11]; //the new population double fitness_Pop[10]; //to save the fitness of all individuals double fitness_Pop_inv[10]; //the inverse of the fitness -> to minimize /////////////////////////// #define rando() ((double)rand()/RAND_MAX) //random number // functions /////////////// void initpop(void); void eval_fitness(void); void print_pop(void); void print_fitness(void); void selection(void); /////////////////////////// int main(void) { int i,j; int generation = 0; int minimum; double min_temp; int pos_min; srand(5); //init random //generate initial population initpop(); //pirnt initial population print_pop(); do { printf("gen %d\n",generation); //evaluate fitness of each individual, only the first time eval_fitness(); //find the minimum min_temp = fitness_Pop[0]; pos_min = 0; for(i=1; i< population; i++) { if(fitness_Pop[i] < min_temp) { min_temp = fitness_Pop[i]; pos_min = i; } } // printf the best individual found printf("fitness best %f\n",min_temp); printf("pos min %d\n Best individual found\n",pos_min); for(i=0; i maxGen) || (min_temp == 0)) break; //stop the algorithm //print the fitness of each individual if(band==1)print_fitness(); //select parents, apply crossover and mutate selection(); //replace the old population by the offspring for(i=0; i