导航:首页 > 源码编译 > 遗传算法程序

遗传算法程序

发布时间:2022-01-20 11:57:46

A. matlab遗传算法程序

在matlab里没有
for
i
=
1
to
80
...
endfor
这样的语法的
在matlab里应该是:
for
i
=
1:
1:
80
...
end
1:1:80
第一个1是初始值,第二个是每次+1的意思
当然如果是我古若寡闻那也请见谅~~哈哈~~

B. 遗传算法程序

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/* Change any of these parameters to match your needs */

#define POPSIZE 50 /* population size */
#define MAXGENS 1000 /* max. number of generations */
#define NVARS 3 /* no. of problem variables */
#define PXOVER 0.8 /* probability of crossover */
#define PMUTATION 0.15 /* probability of mutation */
#define TRUE 1
#define FALSE 0

int generation; /* current generation no. */
int cur_best; /* best indivial */
FILE *galog; /* an output file */

struct genotype /* genotype (GT), a member of the population */
{
double gene[NVARS]; /* a string of variables */
double fitness; /* GT's fitness */
double upper[NVARS]; /* GT's variables upper bound */
double lower[NVARS]; /* GT's variables lower bound */
double rfitness; /* relative fitness */
double cfitness; /* cumulative fitness */
};

struct genotype population[POPSIZE+1]; /* population */
struct genotype newpopulation[POPSIZE+1]; /* new population; */
/* replaces the */
/* old generation */

/* Declaration of proceres used by this genetic algorithm */

void initialize(void);
double randval(double, double);
void evaluate(void);
void keep_the_best(void);
void elitist(void);
void select(void);
void crossover(void);
void Xover(int,int);
void swap(double *, double *);
void mutate(void);
void report(void);

/***************************************************************/
/* Initialization function: Initializes the values of genes */
/* within the variables bounds. It also initializes (to zero) */
/* all fitness values for each member of the population. It */
/* reads upper and lower bounds of each variable from the */
/* input file `gadata.txt'. It randomly generates values */
/* between these bounds for each gene of each genotype in the */
/* population. The format of the input file `gadata.txt' is */
/* var1_lower_bound var1_upper bound */
/* var2_lower_bound var2_upper bound ... */
/***************************************************************/

void initialize(void)
{
FILE *infile;
int i, j;
double lbound, ubound;

if ((infile = fopen("gadata.txt","r"))==NULL)
{
fprintf(galog,"\nCannot open input file!\n");
exit(1);
}

/* initialize variables within the bounds */

for (i = 0; i < NVARS; i++)
{
fscanf(infile, "%lf",&lbound);
fscanf(infile, "%lf",&ubound);

for (j = 0; j < POPSIZE; j++)
{
population[j].fitness = 0;
population[j].rfitness = 0;
population[j].cfitness = 0;
population[j].lower[i] = lbound;
population[j].upper[i]= ubound;
population[j].gene[i] = randval(population[j].lower[i],
population[j].upper[i]);
}
}

fclose(infile);
}

/***********************************************************/
/* Random value generator: Generates a value within bounds */
/***********************************************************/

double randval(double low, double high)
{
double val;
val = ((double)(rand()%1000)/1000.0)*(high - low) + low;
return(val);
}

/*************************************************************/
/* Evaluation function: This takes a user defined function. */
/* Each time this is changed, the code has to be recompiled. */
/* The current function is: x[1]^2-x[1]*x[2]+x[3] */
/*************************************************************/

void evaluate(void)
{
int mem;
int i;
double x[NVARS+1];

for (mem = 0; mem < POPSIZE; mem++)
{
for (i = 0; i < NVARS; i++)
x[i+1] = population[mem].gene[i];

population[mem].fitness = (x[1]*x[1]) - (x[1]*x[2]) + x[3];
}
}

/***************************************************************/
/* Keep_the_best function: This function keeps track of the */
/* best member of the population. Note that the last entry in */
/* the array Population holds a of the best indivial */
/***************************************************************/

void keep_the_best()
{
int mem;
int i;
cur_best = 0; /* stores the index of the best indivial */

for (mem = 0; mem < POPSIZE; mem++)
{
if (population[mem].fitness > population[POPSIZE].fitness)
{
cur_best = mem;
population[POPSIZE].fitness = population[mem].fitness;
}
}
/* once the best member in the population is found, the genes */
for (i = 0; i < NVARS; i++)
population[POPSIZE].gene[i] = population[cur_best].gene[i];
}

/****************************************************************/
/* Elitist function: The best member of the previous generation */
/* is stored as the last in the array. If the best member of */
/* the current generation is worse then the best member of the */
/* previous generation, the latter one would replace the worst */
/* member of the current population */
/****************************************************************/

void elitist()
{
int i;
double best, worst; /* best and worst fitness values */
int best_mem, worst_mem; /* indexes of the best and worst member */

best = population[0].fitness;
worst = population[0].fitness;
for (i = 0; i < POPSIZE - 1; ++i)
{
if(population[i].fitness > population[i+1].fitness)
{
if (population[i].fitness >= best)
{
best = population[i].fitness;
best_mem = i;
}
if (population[i+1].fitness <= worst)
{
worst = population[i+1].fitness;
worst_mem = i + 1;
}
}
else
{
if (population[i].fitness <= worst)
{
worst = population[i].fitness;
worst_mem = i;
}
if (population[i+1].fitness >= best)
{
best = population[i+1].fitness;
best_mem = i + 1;
}
}
}
/* if best indivial from the new population is better than */
/* the best indivial from the previous population, then */
/* the best from the new population; else replace the */
/* worst indivial from the current population with the */
/* best one from the previous generation */

if (best >= population[POPSIZE].fitness)
{
for (i = 0; i < NVARS; i++)
population[POPSIZE].gene[i] = population[best_mem].gene[i];
population[POPSIZE].fitness = population[best_mem].fitness;
}
else
{
for (i = 0; i < NVARS; i++)
population[worst_mem].gene[i] = population[POPSIZE].gene[i];
population[worst_mem].fitness = population[POPSIZE].fitness;
}
}
/**************************************************************/
/* Selection function: Standard proportional selection for */
/* maximization problems incorporating elitist model - makes */
/* sure that the best member survives */
/**************************************************************/

void select(void)
{
int mem, i, j, k;
double sum = 0;
double p;

/* find total fitness of the population */
for (mem = 0; mem < POPSIZE; mem++)
{
sum += population[mem].fitness;
}

/* calculate relative fitness */
for (mem = 0; mem < POPSIZE; mem++)
{
population[mem].rfitness = population[mem].fitness/sum;
}
population[0].cfitness = population[0].rfitness;

/* calculate cumulative fitness */
for (mem = 1; mem < POPSIZE; mem++)
{
population[mem].cfitness = population[mem-1].cfitness +
population[mem].rfitness;
}

/* finally select survivors using cumulative fitness. */

for (i = 0; i < POPSIZE; i++)
{
p = rand()%1000/1000.0;
if (p < population[0].cfitness)
newpopulation[i] = population[0];
else
{
for (j = 0; j < POPSIZE;j++)
if (p >= population[j].cfitness &&
p<population[j+1].cfitness)
newpopulation[i] = population[j+1];
}
}
/* once a new population is created, it back */

for (i = 0; i < POPSIZE; i++)
population[i] = newpopulation[i];
}

/***************************************************************/
/* Crossover selection: selects two parents that take part in */
/* the crossover. Implements a single point crossover */
/***************************************************************/

void crossover(void)
{
int i, mem, one;
int first = 0; /* count of the number of members chosen */
double x;

for (mem = 0; mem < POPSIZE; ++mem)
{
x = rand()%1000/1000.0;
if (x < PXOVER)
{
++first;
if (first % 2 == 0)
Xover(one, mem);
else
one = mem;
}
}
}
/**************************************************************/
/* Crossover: performs crossover of the two selected parents. */
/**************************************************************/

void Xover(int one, int two)
{
int i;
int point; /* crossover point */

/* select crossover point */
if(NVARS > 1)
{
if(NVARS == 2)
point = 1;
else
point = (rand() % (NVARS - 1)) + 1;

for (i = 0; i < point; i++)
swap(&population[one].gene[i], &population[two].gene[i]);

}
}

/*************************************************************/
/* Swap: A swap procere that helps in swapping 2 variables */
/*************************************************************/

void swap(double *x, double *y)
{
double temp;

temp = *x;
*x = *y;
*y = temp;

}

/**************************************************************/
/* Mutation: Random uniform mutation. A variable selected for */
/* mutation is replaced by a random value between lower and */
/* upper bounds of this variable */
/**************************************************************/

void mutate(void)
{
int i, j;
double lbound, hbound;
double x;

for (i = 0; i < POPSIZE; i++)
for (j = 0; j < NVARS; j++)
{
x = rand()%1000/1000.0;
if (x < PMUTATION)
{
/* find the bounds on the variable to be mutated */
lbound = population[i].lower[j];
hbound = population[i].upper[j];
population[i].gene[j] = randval(lbound, hbound);
}
}
}

/***************************************************************/
/* Report function: Reports progress of the simulation. Data */
/* mped into the output file are separated by commas */
/***************************************************************/

void report(void)
{
int i;
double best_val; /* best population fitness */
double avg; /* avg population fitness */
double stddev; /* std. deviation of population fitness */
double sum_square; /* sum of square for std. calc */
double square_sum; /* square of sum for std. calc */
double sum; /* total population fitness */

sum = 0.0;
sum_square = 0.0;

for (i = 0; i < POPSIZE; i++)
{
sum += population[i].fitness;
sum_square += population[i].fitness * population[i].fitness;
}

avg = sum/(double)POPSIZE;
square_sum = avg * avg * POPSIZE;
stddev = sqrt((sum_square - square_sum)/(POPSIZE - 1));
best_val = population[POPSIZE].fitness;

fprintf(galog, "\n%5d, %6.3f, %6.3f, %6.3f \n\n", generation,
best_val, avg, stddev);
}

/**************************************************************/
/* Main function: Each generation involves selecting the best */
/* members, performing crossover & mutation and then */
/* evaluating the resulting population, until the terminating */
/* condition is satisfied */
/**************************************************************/

void main(void)
{
int i;

if ((galog = fopen("galog.txt","w"))==NULL)
{
exit(1);
}
generation = 0;

fprintf(galog, "\n generation best average standard \n");
fprintf(galog, " number value fitness deviation \n");

initialize();
evaluate();
keep_the_best();
while(generation<MAXGENS)
{
generation++;
select();
crossover();
mutate();
report();
evaluate();
elitist();
}
fprintf(galog,"\n\n Simulation completed\n");
fprintf(galog,"\n Best member: \n");

for (i = 0; i < NVARS; i++)
{
fprintf (galog,"\n var(%d) = %3.3f",i,population[POPSIZE].gene[i]);
}
fprintf(galog,"\n\n Best fitness = %3.3f",population[POPSIZE].fitness);
fclose(galog);
printf("Success\n");
}
/***************************************************************/

C. 遗传算法的matlab代码实现是什么

遗传算法我懂,我的论文就是用着这个算法,具体到你要遗传算法是做什么?优化什么的。。。我给你一个标准遗传算法程序供你参考:
该程序是遗传算法优化BP神经网络函数极值寻优:
%% 该代码为基于神经网络遗传算法的系统极值寻优
%% 清空环境变量
clc
clear

%% 初始化遗传算法参数
%初始化参数
maxgen=100; %进化代数,即迭代次数
sizepop=20; %种群规模
pcross=[0.4]; %交叉概率选择,0和1之间
pmutation=[0.2]; %变异概率选择,0和1之间

lenchrom=[1 1]; %每个变量的字串长度,如果是浮点变量,则长度都为1
bound=[-5 5;-5 5]; %数据范围

indivials=struct('fitness',zeros(1,sizepop), 'chrom',[]); %将种群信息定义为一个结构体
avgfitness=[]; %每一代种群的平均适应度
bestfitness=[]; %每一代种群的最佳适应度
bestchrom=[]; %适应度最好的染色体

%% 初始化种群计算适应度值
% 初始化种群
for i=1:sizepop
%随机产生一个种群
indivials.chrom(i,:)=Code(lenchrom,bound);
x=indivials.chrom(i,:);
%计算适应度
indivials.fitness(i)=fun(x); %染色体的适应度
end
%找最好的染色体
[bestfitness bestindex]=min(indivials.fitness);
bestchrom=indivials.chrom(bestindex,:); %最好的染色体
avgfitness=sum(indivials.fitness)/sizepop; %染色体的平均适应度
% 记录每一代进化中最好的适应度和平均适应度
trace=[avgfitness bestfitness];

%% 迭代寻优
% 进化开始
for i=1:maxgen
i
% 选择
indivials=Select(indivials,sizepop);
avgfitness=sum(indivials.fitness)/sizepop;
%交叉
indivials.chrom=Cross(pcross,lenchrom,indivials.chrom,sizepop,bound);
% 变异
indivials.chrom=Mutation(pmutation,lenchrom,indivials.chrom,sizepop,[i maxgen],bound);

% 计算适应度
for j=1:sizepop
x=indivials.chrom(j,:); %解码
indivials.fitness(j)=fun(x);
end

%找到最小和最大适应度的染色体及它们在种群中的位置
[newbestfitness,newbestindex]=min(indivials.fitness);
[worestfitness,worestindex]=max(indivials.fitness);
% 代替上一次进化中最好的染色体
if bestfitness>newbestfitness
bestfitness=newbestfitness;
bestchrom=indivials.chrom(newbestindex,:);
end
indivials.chrom(worestindex,:)=bestchrom;
indivials.fitness(worestindex)=bestfitness;

avgfitness=sum(indivials.fitness)/sizepop;

trace=[trace;avgfitness bestfitness]; %记录每一代进化中最好的适应度和平均适应度
end
%进化结束

%% 结果分析
[r c]=size(trace);
plot([1:r]',trace(:,2),'r-');
title('适应度曲线','fontsize',12);
xlabel('进化代数','fontsize',12);ylabel('适应度','fontsize',12);
axis([0,100,0,1])
disp('适应度 变量');
x=bestchrom;
% 窗口显示
disp([bestfitness x]);

D. 遗传算法C++程序

。。。。估计你这样问不会有人懂的,上网的人很少会遗传算法的,就算是学计算机和软件的也很少用这类概率优化算法,再者,一般写遗传用matlab很多,而且资料也多。。。。用c/c++能写出来的都是很变态的高手。。。

E. 遗传算法 简单程序应用

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

class Best {
public int generations; //最佳适应值代号
public String str; //最佳染色体
public double fitness; //最佳适应值
}

public class SGAFrame extends JFrame {

private JTextArea textArea;
private String str = "";
private Best best = null; //最佳染色体
private String[] ipop = new String[10]; //染色体
private int gernation = 0; //染色体代号
public static final int GENE = 22; //基因数
/**
* Launch the application
* @param args
*/
public static void main(String args[]) {
try {
SGAFrame frame = new SGAFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* Create the frame
*/
public SGAFrame() {
super();

this.ipop = inialPops();

getContentPane().setLayout(null);
setBounds(100, 100, 461, 277);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final JLabel label = new JLabel();
label.setText("X的区间:");
label.setBounds(23, 10, 88, 15);
getContentPane().add(label);

final JLabel label_1 = new JLabel();
label_1.setText("[-255,255]");
label_1.setBounds(92, 10, 84, 15);
getContentPane().add(label_1);

final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
SGAFrame s = new SGAFrame();
str = str + s.process() + "\n";
textArea.setText(str);
}
});
button.setText("求最小值");
button.setBounds(323, 27, 99, 23);
getContentPane().add(button);

final JLabel label_2 = new JLabel();
label_2.setText("利用标准遗传算法求解函数f(x)=(x-5)*(x-5)的最小值:");
label_2.setBounds(23, 31, 318, 15);
getContentPane().add(label_2);

final JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBounds(23, 65, 399, 164);
getContentPane().add(panel);

final JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane, BorderLayout.CENTER);

textArea = new JTextArea();
scrollPane.setViewportView(textArea);
//
}

/**
* 初始化一条染色体(用二进制字符串表示)
* @return 一条染色体
*/
private String inialPop() {
String res = "";
for (int i = 0; i < GENE; i++) {
if (Math.random() > 0.5) {
res += "0";
} else {
res += "1";
}
}
return res;
}

/**
* 初始化一组染色体
* @return 染色体组
*/
private String[] inialPops() {
String[] ipop = new String[10];
for (int i = 0; i < 10; i++) {
ipop[i] = inialPop();
}
return ipop;
}

/**
* 将染色体转换成x的值
* @param str 染色体
* @return 染色体的适应值
*/
private double calculatefitnessvalue(String str) {
int b = Integer.parseInt(str, 2);
//String str1 = "" + "/n";
double x = -255 + b * (255 - (-255)) / (Math.pow(2, GENE) - 1);
//System.out.println("X = " + x);
double fitness = -(x - 5) * (x - 5);
//System.out.println("f(x)=" + fitness);
//str1 = str1 + "X=" + x + "/n"
//+ "f(x)=" + "fitness" + "/n";
//textArea.setText(str1);

return fitness;
}

/**
* 计算群体上每个个体的适应度值;
* 按由个体适应度值所决定的某个规则选择将进入下一代的个体;
*/
private void select() {
double evals[] = new double[10]; // 所有染色体适应值
double p[] = new double[10]; // 各染色体选择概率
double q[] = new double[10]; // 累计概率
double F = 0; // 累计适应值总和
for (int i = 0; i < 10; i++) {
evals[i] = calculatefitnessvalue(ipop[i]);
if (best == null) {
best = new Best();
best.fitness = evals[i];
best.generations = 0;
best.str = ipop[i];
} else {
if (evals[i] > best.fitness) // 最好的记录下来
{
best.fitness = evals[i];
best.generations = gernation;
best.str = ipop[i];
}
}
F = F + evals[i]; // 所有染色体适应值总和

}
for (int i = 0; i < 10; i++) {
p[i] = evals[i] / F;
if (i == 0)
q[i] = p[i];
else {
q[i] = q[i - 1] + p[i];
}
}
for (int i = 0; i < 10; i++) {

double r = Math.random();
if (r <= q[0]) {
ipop[i] = ipop[0];

} else {
for (int j = 1; j < 10; j++) {
if (r < q[j]) {
ipop[i] = ipop[j];
break;
}
}
}
}
}

/**
* 交叉操作
* 交叉率为25%,平均为25%的染色体进行交叉
*/
private void cross() {
String temp1, temp2;
for (int i = 0; i < 10; i++) {
if (Math.random() < 0.25) {
double r = Math.random();
int pos = (int) (Math.round(r * 1000)) % GENE;
if (pos == 0) {
pos = 1;
}
temp1 = ipop[i].substring(0, pos)
+ ipop[(i + 1) % 10].substring(pos);
temp2 = ipop[(i + 1) % 10].substring(0, pos)
+ ipop[i].substring(pos);
ipop[i] = temp1;
ipop[(i + 1) / 10] = temp2;
}
}
}

/**
* 基因突变操作
* 1%基因变异m*pop_size 共180个基因,为了使每个基因都有相同机会发生变异,
* 需要产生[1--180]上均匀分布的
*/
private void mutation() {
for (int i = 0; i < 4; i++) {
int num = (int) (Math.random() * GENE * 10 + 1);
int chromosomeNum = (int) (num / GENE) + 1; // 染色体号

int mutationNum = num - (chromosomeNum - 1) * GENE; // 基因号
if (mutationNum == 0)
mutationNum = 1;
chromosomeNum = chromosomeNum - 1;
if (chromosomeNum >= 10)
chromosomeNum = 9;
//System.out.println("变异前" + ipop[chromosomeNum]);
String temp;
if (ipop[chromosomeNum].charAt(mutationNum - 1) == '0') {
if (mutationNum == 1) {
temp = "1" + ipop[chromosomeNum].substring

(mutationNum);
} else {
if (mutationNum != GENE) {
temp = ipop[chromosomeNum].substring(0, mutationNum -

1) + "1" + ipop

[chromosomeNum].substring(mutationNum);
} else {
temp = ipop[chromosomeNum].substring(0, mutationNum -
1) + "1";
}
}
} else {
if (mutationNum == 1) {
temp = "0" + ipop[chromosomeNum].substring

(mutationNum);
} else {
if (mutationNum != GENE) {
temp = ipop[chromosomeNum].substring(0, mutationNum -

1) + "0" + ipop

[chromosomeNum].substring(mutationNum);
} else {
temp = ipop[chromosomeNum].substring(0, mutationNum -
1) + "1";
}
}
}
ipop[chromosomeNum] = temp;
//System.out.println("变异后" + ipop[chromosomeNum]);
}
}
/**
* 执行遗传算法
*/
public String process() {
String str = "";
for (int i = 0; i < 10000; i++) {
this.select();
this.cross();
this.mutation();
gernation = i;
}
str = "最小值" + best.fitness + ",第" + best.generations + "个染色体";
return str;
}

}

F. MATLAB编遗传算法源程序

遗传算法实例:

也是自己找来的,原代码有少许错误,本人都已更正了,调试运行都通过了的。
对于初学者,尤其是还没有编程经验的非常有用的一个文件
遗传算法实例

% 下面举例说明遗传算法 %
% 求下列函数的最大值 %
% f(x)=10*sin(5x)+7*cos(4x) x∈[0,10] %
% 将 x 的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为 (10-0)/(2^10-1)≈0.01 。 %
% 将变量域 [0,10] 离散化为二值域 [0,1023], x=0+10*b/1023, 其中 b 是 [0,1023] 中的一个二值数。 %
% %
%--------------------------------------------------------------------------------------------------------------%
%--------------------------------------------------------------------------------------------------------------%

% 编程
%-----------------------------------------------
% 2.1初始化(编码)
% initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二值数的长度),
% 长度大小取决于变量的二进制编码的长度(在本例中取10位)。
%遗传算法子程序
%Name: initpop.m
%初始化
function pop=initpop(popsize,chromlength)
pop=round(rand(popsize,chromlength)); % rand随机产生每个单元为 {0,1} 行数为popsize,列数为chromlength的矩阵,
% roud对矩阵的每个单元进行圆整。这样产生的初始种群。

% 2.2 计算目标函数值
% 2.2.1 将二进制数转化为十进制数(1)
%遗传算法子程序
%Name: decodebinary.m
%产生 [2^n 2^(n-1) ... 1] 的行向量,然后求和,将二进制转化为十进制
function pop2=decodebinary(pop)
[px,py]=size(pop); %求pop行和列数
for i=1:py
pop1(:,i)=2.^(py-i).*pop(:,i);
end
pop2=sum(pop1,2); %求pop1的每行之和

% 2.2.2 将二进制编码转化为十进制数(2)
% decodechrom.m函数的功能是将染色体(或二进制编码)转换为十进制,参数spoint表示待解码的二进制串的起始位置
% (对于多个变量而言,如有两个变量,采用20为表示,每个变量10为,则第一个变量从1开始,另一个变量从11开始。本例为1),
% 参数1ength表示所截取的长度(本例为10)。
%遗传算法子程序
%Name: decodechrom.m
%将二进制编码转换成十进制
function pop2=decodechrom(pop,spoint,length)
pop1=pop(:,spoint:spoint+length-1);
pop2=decodebinary(pop1);

% 2.2.3 计算目标函数值
% calobjvalue.m函数的功能是实现目标函数的计算,其公式采用本文示例仿真,可根据不同优化问题予以修改。
%遗传算法子程序
%Name: calobjvalue.m
%实现目标函数的计算
function [objvalue]=calobjvalue(pop)
temp1=decodechrom(pop,1,10); %将pop每行转化成十进制数
x=temp1*10/1023; %将二值域 中的数转化为变量域 的数
objvalue=10*sin(5*x)+7*cos(4*x); %计算目标函数值

% 2.3 计算个体的适应值
%遗传算法子程序
%Name:calfitvalue.m
%计算个体的适应值
function fitvalue=calfitvalue(objvalue)
global Cmin;
Cmin=0;
[px,py]=size(objvalue);
for i=1:px
if objvalue(i)+Cmin>0
temp=Cmin+objvalue(i);
else
temp=0.0;
end
fitvalue(i)=temp;
end
fitvalue=fitvalue';

% 2.4 选择复制
% 选择或复制操作是决定哪些个体可以进入下一代。程序中采用赌轮盘选择法选择,这种方法较易实现。
% 根据方程 pi=fi/∑fi=fi/fsum ,选择步骤:
% 1) 在第 t 代,由(1)式计算 fsum 和 pi
% 2) 产生 {0,1} 的随机数 rand( .),求 s=rand( .)*fsum
% 3) 求 ∑fi≥s 中最小的 k ,则第 k 个个体被选中
% 4) 进行 N 次2)、3)操作,得到 N 个个体,成为第 t=t+1 代种群
%遗传算法子程序
%Name: selection.m
%选择复制
function [newpop]=selection(pop,fitvalue)
totalfit=sum(fitvalue); %求适应值之和
fitvalue=fitvalue/totalfit; %单个个体被选择的概率
fitvalue=cumsum(fitvalue); %如 fitvalue=[1 2 3 4],则 cumsum(fitvalue)=[1 3 6 10]
[px,py]=size(pop);
ms=sort(rand(px,1)); %从小到大排列
fitin=1;
newin=1;
while newin<=px
if(ms(newin))<fitvalue(fitin)
newpop(newin)=pop(fitin);
newin=newin+1;
else
fitin=fitin+1;
end
end

% 2.5 交叉
% 交叉(crossover),群体中的每个个体之间都以一定的概率 pc 交叉,即两个个体从各自字符串的某一位置
% (一般是随机确定)开始互相交换,这类似生物进化过程中的基因分裂与重组。例如,假设2个父代个体x1,x2为:
% x1=0100110
% x2=1010001
% 从每个个体的第3位开始交叉,交又后得到2个新的子代个体y1,y2分别为:
% y1=0100001
% y2=1010110
% 这样2个子代个体就分别具有了2个父代个体的某些特征。利用交又我们有可能由父代个体在子代组合成具有更高适合度的个体。
% 事实上交又是遗传算法区别于其它传统优化方法的主要特点之一。
%遗传算法子程序
%Name: crossover.m
%交叉
function [newpop]=crossover(pop,pc)
[px,py]=size(pop);
newpop=ones(size(pop));
for i=1:2:px-1
if(rand<pc)
cpoint=round(rand*py);
newpop(i,:)=[pop(i,1:cpoint),pop(i+1,cpoint+1:py)];
newpop(i+1,:)=[pop(i+1,1:cpoint),pop(i,cpoint+1:py)];
else
newpop(i,:)=pop(i);
newpop(i+1,:)=pop(i+1);
end
end

% 2.6 变异
% 变异(mutation),基因的突变普遍存在于生物的进化过程中。变异是指父代中的每个个体的每一位都以概率 pm 翻转,即由“1”变为“0”,
% 或由“0”变为“1”。遗传算法的变异特性可以使求解过程随机地搜索到解可能存在的整个空间,因此可以在一定程度上求得全局最优解。
%遗传算法子程序
%Name: mutation.m
%变异
function [newpop]=mutation(pop,pm)
[px,py]=size(pop);
newpop=ones(size(pop));
for i=1:px
if(rand<pm)
mpoint=round(rand*py);
if mpoint<=0
mpoint=1;
end
newpop(i)=pop(i);
if any(newpop(i,mpoint))==0
newpop(i,mpoint)=1;
else
newpop(i,mpoint)=0;
end
else
newpop(i)=pop(i);
end
end

% 2.7 求出群体中最大得适应值及其个体
%遗传算法子程序
%Name: best.m
%求出群体中适应值最大的值
function [bestindivial,bestfit]=best(pop,fitvalue)
[px,py]=size(pop);
bestindivial=pop(1,:);
bestfit=fitvalue(1);
for i=2:px
if fitvalue(i)>bestfit
bestindivial=pop(i,:);
bestfit=fitvalue(i);
end
end

% 2.8 主程序
%遗传算法主程序
%Name:genmain05.m
clear
clf
popsize=20; %群体大小
chromlength=10; %字符串长度(个体长度)
pc=0.6; %交叉概率
pm=0.001; %变异概率

pop=initpop(popsize,chromlength); %随机产生初始群体
for i=1:20 %20为迭代次数
[objvalue]=calobjvalue(pop); %计算目标函数
fitvalue=calfitvalue(objvalue); %计算群体中每个个体的适应度
[newpop]=selection(pop,fitvalue); %复制
[newpop]=crossover(pop,pc); %交叉
[newpop]=mutation(pop,pc); %变异
[bestindivial,bestfit]=best(pop,fitvalue); %求出群体中适应值最大的个体及其适应值
y(i)=max(bestfit);
n(i)=i;
pop5=bestindivial;
x(i)=decodechrom(pop5,1,chromlength)*10/1023;
pop=newpop;
end

fplot('10*sin(5*x)+7*cos(4*x)',[0 10])
hold on
plot(x,y,'r*')
hold off

[z index]=max(y); %计算最大值及其位置
x5=x(index)%计算最大值对应的x值
y=z

【问题】求f(x)=x 10*sin(5x) 7*cos(4x)的最大值,其中0<=x<=9
【分析】选择二进制编码,种群中的个体数目为10,二进制编码长度为20,交叉概率为0.95,变异概率为0.08
【程序清单】
%编写目标函数
function[sol,eval]=fitness(sol,options)
x=sol(1);
eval=x 10*sin(5*x) 7*cos(4*x);
%把上述函数存储为fitness.m文件并放在工作目录下
initPop=initializega(10,[0 9],'fitness');%生成初始种群,大小为10
[x endPop,bPop,trace]=ga([0 9],'fitness',[],initPop,[1e-6 1 1],'maxGenTerm',25,'normGeomSelect',...
[0.08],['arithXover'],[2],'nonUnifMutation',[2 25 3]) %25次遗传迭代
运算借过为:x =
7.8562 24.8553(当x为7.8562时,f(x)取最大值24.8553)
注:遗传算法一般用来取得近似最优解,而不是最优解。
遗传算法实例2
【问题】在-5<=Xi<=5,i=1,2区间内,求解
f(x1,x2)=-20*exp(-0.2*sqrt(0.5*(x1.^2 x2.^2)))-exp(0.5*(cos(2*pi*x1) cos(2*pi*x2))) 22.71282的最小值。
【分析】种群大小10,最大代数1000,变异率0.1,交叉率0.3
【程序清单】
%源函数的matlab代码
function [eval]=f(sol)
numv=size(sol,2);
x=sol(1:numv);
eval=-20*exp(-0.2*sqrt(sum(x.^2)/numv)))-exp(sum(cos(2*pi*x))/numv) 22.71282;
%适应度函数的matlab代码
function [sol,eval]=fitness(sol,options)
numv=size(sol,2)-1;
x=sol(1:numv);
eval=f(x);
eval=-eval;
%遗传算法的matlab代码
bounds=ones(2,1)*[-5 5];
[p,endPop,bestSols,trace]=ga(bounds,'fitness')
注:前两个文件存储为m文件并放在工作目录下,运行结果为
p =
0.0000 -0.0000 0.0055
大家可以直接绘出f(x)的图形来大概看看f(x)的最值是多少,也可是使用优化函数来验证。matlab命令行执行命令:
fplot('x 10*sin(5*x) 7*cos(4*x)',[0,9])
evalops是传递给适应度函数的参数,opts是二进制编码的精度,termops是选择maxGenTerm结束函数时传递个maxGenTerm的参数,即遗传代数。xoverops是传递给交叉函数的参数。mutops是传递给变异函数的参数。

【问题】求f(x)=x+10*sin(5x)+7*cos(4x)的最大值,其中0<=x<=9
【分析】选择二进制编码,种群中的个体数目为10,二进制编码长度为20,交叉概率为0.95,变异概率为0.08
【程序清单】
%编写目标函数
function[sol,eval]=fitness(sol,options)
x=sol(1);
eval=x+10*sin(5*x)+7*cos(4*x);
%把上述函数存储为fitness.m文件并放在工作目录下
initPop=initializega(10,[0 9],'fitness');%生成初始种群,大小为10
[x endPop,bPop,trace]=ga([0 9],'fitness',[],initPop,[1e-6 1 1],'maxGenTerm',25,'normGeomSelect',...
[0.08],['arithXover'],[2],'nonUnifMutation',[2 25 3]) %25次遗传迭代
运算借过为:x =
7.8562 24.8553(当x为7.8562时,f(x)取最大值24.8553)
注:遗传算法一般用来取得近似最优解,而不是最优解。
遗传算法实例2
【问题】在-5<=Xi<=5,i=1,2区间内,求解
f(x1,x2)=-20*exp(-0.2*sqrt(0.5*(x1.^2+x2.^2)))-exp(0.5*(cos(2*pi*x1)+cos(2*pi*x2)))+22.71282的最小值。
【分析】种群大小10,最大代数1000,变异率0.1,交叉率0.3
【程序清单】
%源函数的matlab代码
function [eval]=f(sol)
numv=size(sol,2);
x=sol(1:numv);
eval=-20*exp(-0.2*sqrt(sum(x.^2)/numv)))-exp(sum(cos(2*pi*x))/numv)+22.71282;
%适应度函数的matlab代码
function [sol,eval]=fitness(sol,options)
numv=size(sol,2)-1;
x=sol(1:numv);
eval=f(x);
eval=-eval;
%遗传算法的matlab代码
bounds=ones(2,1)*[-5 5];
[p,endPop,bestSols,trace]=ga(bounds,'fitness')
注:前两个文件存储为m文件并放在工作目录下,运行结果为
p =
0.0000 -0.0000 0.0055
大家可以直接绘出f(x)的图形来大概看看f(x)的最值是多少,也可是使用优化函数来验证。matlab命令行执行命令:
fplot('x+10*sin(5*x)+7*cos(4*x)',[0,9])
evalops是传递给适应度函数的参数,opts是二进制编码的精度,termops是选择maxGenTerm结束函数时传递个maxGenTerm的参数,即遗传代数。xoverops是传递给交叉函数的参数。mutops是传递给变异函数的参数。

G. 遗传算法程序运行这个该用什么软件能运行

MATLAB用于图像建模算法的设计和运行
这个用MATLAB实现可以运行。

H. 高分求遗传算法程序

遗传算法作为一种快速有效的寻优算法,在工业控制、经济决策和交通规划等居多领域得到广泛应用。其特点就是其不同于传统的搜索寻优方式而是模拟自然界生物进化过程,通过基因的变异交叉重组使整体得到进化,不断的进化最终得到最优的组群,即最优解。
下面是一个具体实例,是小可在别人程序的基础上改写优化而成。这里首先要建立数学模型,即问题的数学公式描述,数学建模是一门对数学能力有相当要求的课程,一个人的数学能力往往决定其从事工作的层次。下面的程序是求多项式y=x^6-10x^5-26x^4+344x^3+193x^2-1846x-1680在区间[-8,8]的最小值,误差不超过0.001。对于这个复杂的多项式,可先用matlab绘制函数的大概曲线,确认函数的最小值大概处于[-8,8]之间,再用本程序求出精确解。
程序已在Dev-c++下运行通过,结果正确。
如有什么疑问,给我消息。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#define SUM 20 /* 总共的染色体数量 */
#define MAXloop 1200 /* 最大循环次数 */
#define error 0.01 /* 若两次最优值之差小于此数则认为结果没有改变 */
#define crossp 0.7 /* 交叉概率 */
#define mp 0.04 /* 变异概率 */

struct gen /* 定义染色体结构 */
{
int info;
double suitability;
};
struct gen gen_group[SUM];/* 定义一个含有20个染色体的组 */
struct gen gen_new[SUM];

struct gen gen_result; /* 记录最优的染色体 */
int result_unchange_time; /* 记录在error前提下最优值未改变的循环次数 */

struct log /* 形成链表,记录每次循环所产生的最优的适应度 */
{
double suitability;
struct log *next;
}llog,*head,*end;
int log_num; /* 链表长度 */

void initiate(); /*初始化函数*/
void evaluation(int flag); /*适应度评估和排序函数*/
void cross(); /*交叉函数*/
void selection(); /*选择函数*/
int record(); /*记录每次最优解和判断循环是否终止*/
void mutation(); /*变异函数*/
void showresult(int); /*显示结果*/

int randsign(double p); /*按概率p产生0,1随机数,p表示产生值1的概率*/
int randbit(int i,int j);/*产生i,j间的随机整数*/
int randnum(); /*随机产生14个位(基因)组成的染色体*/
int convertionD2B(double x); /*编码*/
double convertionB2D(int x); /*解码*/
int createmask(int a); /*交叉操作*/

int main()
{
int i,flag;
flag=0;
initiate();
evaluation( 0 );
for( i = 0 ; i < MAXloop ; i++ )
{
cross();
evaluation( 1 );
selection();
if( record() == 1 )
{
flag = 1;
break;
}
mutation();
}
showresult( flag );
system("pause");
return 0
}

void initiate()
{
int i , stime;
long ltime;
ltime=time(NULL);
stime=(unsigned)ltime/2;
srand(stime);
for( i = 0 ; i < SUM ; i++ )
{
gen_group[i].info = randnum();
}
gen_result.suitability=1000;
result_unchange_time=0;
head=end=(struct log *)malloc(sizeof(llog));
if(head==NULL)
{
printf("\n内存不够!\n");
exit(0);
}
end->next = NULL;
log_num = 1;
}

void evaluation(int flag)
{
int i,j,k;
struct gen *genp;
int gentinfo;
double gentsuitability;
double x;
if( flag == 0 )
genp = gen_group;
else genp = gen_new;
for(i = 0 ; i < SUM ; i++)/* 计算各染色体对应的表达式值 */
{
x = convertionB2D( genp[i].info );
genp[i].suitability = x*(x*(x*(x*(x*(x-10)-26)+344)+193)-1846)-1680;
}
for(i = 0 ; i < SUM - 1 ; i++)/* 按表达式的值进行排序 */
{ k=i;
for(j = i + 1 ; j < SUM ; j++)
if( genp[i].suitability > genp[j].suitability ) k=j;
if( k!=i )
{
gentinfo = genp[i].info;
genp[i].info = genp[k].info;
genp[k].info = gentinfo;

gentsuitability = genp[i].suitability;
genp[i].suitability = genp[k].suitability;
genp[k].suitability = gentsuitability;
}
}
}

void cross()
{
int i , j , k ;
int mask1 , mask2;
int a[SUM];
for(i = 0 ; i < SUM ; i++) a[i] = 0;
k = 0;
for(i = 0 ; i < SUM ; i++)
{
if( a[i] == 0)
{
for( ; ; )/* 随机找到一组未进行过交叉的染色体与a[i]交叉 */
{
j = randbit(i + 1 , SUM - 1);
if( a[j] == 0) break;
}
if(randsign(crossp) == 1)
{
mask1 = createmask(randbit(0 , 14-1));
mask2 = ~mask1;
gen_new[k].info = (gen_group[i].info) & mask1 + (gen_group[j].info) & mask2;
gen_new[k+1].info=(gen_group[i].info) & mask2 + (gen_group[j].info) & mask1;
k = k + 2;
}
else
{
gen_new[k].info=gen_group[i].info;
gen_new[k+1].info=gen_group[j].info;
k=k+2;
}
a[i] = a[j] = 1;
}
}
}

void selection()
{
int i , j , k;
j = 0;
i = SUM/2-1;
if(gen_group[i].suitability < gen_new[i].suitability)
{
for(j = 1 ; j < SUM / 2 ; j++)
{
if(gen_group[i+j].suitability > gen_new[i-j].suitability)
break;
}
}
else
if(gen_group[i].suitability>gen_new[i].suitability)
{
for(j=-1;j>-SUM/2;j--)
{
if(gen_group[i+j].suitability<=gen_new[i-j].suitability)
break;
}
}
for(k=j;k<SUM/2+1;k++)
{
gen_group[i+k].info = gen_new[i-k].info;
gen_group[i+k].suitability = gen_new[i-k].suitability;
}
}

int record()
{
double x;
struct log *r;
r=(struct log *)malloc(sizeof(llog));
if(r==NULL)
{
printf("\n内存不够!\n");
exit(0);
}
r->next = NULL;
end->suitability = gen_group[0].suitability;
end->next = r;
end = r;
log_num++;

x = gen_result.suitability - gen_group[0].suitability;
if(x < 0)x = -x;
if(x < error)
{
result_unchange_time++;
if(result_unchange_time >= 20)return 1;
}
else
{
gen_result.info = gen_group[0].info;
gen_result.suitability = gen_group[0].suitability;
result_unchange_time=0;
}
return 0;
}

void mutation()
{
int i , j , k, m;
double x;
double gmp;
int gentinfo;
double gentsuitability;
gmp = 1 - pow(1 - mp , 11);/* 在基因变异概率为mp时整条染色体的变异概率 */
for(i = 0 ; i < SUM ; i++)
{
if(randsign(gmp) == 1)
{
j = randbit(0 , 14);
m = 1 << j;
gen_group[i].info = gen_group[i].info^m;
x = convertionB2D(gen_group[i].info);
gen_group[i].suitability = x*(x*(x*(x*(x*(x-10)-26)+344)+193)-1846)-1680;
}
}
for(i = 0 ; i < SUM - 1 ; i++)
{ k=i;
for(j = i + 1 ; j < SUM ; j++)
if(gen_group[i].suitability > gen_group[j].suitability) k=j;
if(k!=i)
{
gentinfo = gen_group[i].info;
gen_group[i].info = gen_group[k].info;
gen_group[k].info = gentinfo;

gentsuitability = gen_group[i].suitability;
gen_group[i].suitability = gen_group[k].suitability;
gen_group[k].suitability = gentsuitability;
}
}
}

void showresult(int flag)/* 显示搜索结果并释放内存 */
{
int i , j;
struct log *logprint,*logfree;
FILE *logf;
if(flag == 0)
printf("已到最大搜索次数,搜索失败!");
else
{
printf("当取值%f时表达式达到最小值为%f\n",convertionB2D(gen_result.info),gen_result.suitability);
printf("收敛过程记录于文件log.txt");
if((logf = fopen("log.txt" , "w+")) == NULL)
{
printf("Cannot create/open file");
exit(1);
}
logprint=head;
for(i = 0 ; i < log_num ; i = i + 5)/* 对收敛过程进行显示 */
{
for(j = 0 ; (j < 5) & ((i + j) < log_num-1) ; j++)
{
fprintf(logf , "%20f" , logprint->suitability);
logprint=logprint->next;
}
fprintf(logf,"\n\n");
}
}
for(i = 0 ; i< log_num ; i++)/* 释放内存 */
{
logfree=head;
head=head->next;
free(logfree);
}
fclose(logf);
getch();
}

int randsign(double p)/* 按概率p返回1 */
{
if(rand() > (p * 32768))
return 0;
else return 1;
}
int randbit(int i, int j)/* 产生在i与j之间的一个随机数 */
{
int a , l;
l = j - i + 1;
a = i + rand() * l / 32768;
return a;
}
int randnum()
{
int x;
x = rand() / 2;
return x;
}
double convertionB2D(int x)
{
double y;
y = x;
y = (y - 8192) / 1000;
return y;

}
int convertionD2B(double x)
{
int g;
g = (x * 1000) + 8192;
return g;
}
int createmask(int a)
{
int mask;
mask=(1 << a) - 1;
return mask;
}

I. 求遗传算法(GA)C语言代码

.----来个例子,大家好理解..--
基于遗传算法的人工生命模拟
#include<stdio.h>
#include<stdlib.h>
#include<graphics.h>
#include<math.h>
#include<time.h>
#include<string.h>
#include "graph.c"
/* 宏定义 */
#define TL1 20 /* 植物性食物限制时间 */
#define TL2 5 /* 动物性食物限制时间 */
#define NEWFOODS 3 /* 植物性食物每代生成数目 */
#define MUTATION 0.05 /* 变异概率 */
#define G_LENGTH 32 /* 个体染色体长度 */
#define MAX_POP 100 /* 个体总数的最大值 */
#define MAX_FOOD 100 /* 食物总数的最大值 */
#define MAX_WX 60 /* 虚拟环境的长度最大值 */
#define MAX_WY 32 /* 虚拟环境的宽度最大值 */
#define SX1 330 /* 虚拟环境图左上角点x坐标 */
#define SY1 40 /* 虚拟环境图左上角点y坐标 */
#define GX 360 /* 个体数进化图形窗口的左上角点X坐标 */
#define GY 257 /* 个体数进化图形窗口的左上角点Y坐标 */
#define GXR 250 /* 个体数进化图形窗口的长度 */
#define GYR 100 /* 个体数进化图形窗口的宽度 */
#define GSTEP 2 /* 个体数进化图形窗口的X方向步长 */
#define R_LIFE 0.05 /* 初期产生生物数的环境比率 */
#define R_FOOD 0.02 /* 初期产生食物数的环境比率 */
#define SL_MIN 10 /* 个体寿命最小值 */
/* 全局变量 */
unsigned char gene[MAX_POP][G_LENGTH]; /* 遗传基因 */
unsigned char iflg[MAX_POP]; /* 个体死活状态标志变量 */

J. 求matlab遗传算法源程序

matlab自带的有遗传算法工具箱,也就是两个函数,分别是

x=ga(fitnessfcn,nvars,A,b,Aeq,beq,LB,UB,nonlcon,options)
options=gaoptimset('param1',value1,'param2',value2,...)

在帮助文件(doc ga/gaoptimset)里面自己好还看看它的用法就可以了,每一个参数都有详细的说明,应该可以帮助到你。

阅读全文

与遗传算法程序相关的资料

热点内容
工作三年的大专程序员 浏览:726
java毕业设计文献 浏览:140
筹码集中度指标源码 浏览:477
listsortjava 浏览:183
plc闪光电路编程实例 浏览:297
socket编程试题 浏览:203
华为的服务器怎么设置从光驱启动 浏览:867
程序员真的累吗 浏览:324
学信网app为什么刷脸不了 浏览:872
天蝎vs程序员 浏览:991
单片机下载口叫什么 浏览:188
程序员的道 浏览:926
云服务器不实名违法吗 浏览:558
怎样查看文件夹图片是否重复 浏览:995
文件怎么导成pdf文件 浏览:808
打开sql表的命令 浏览:103
安卓手机如何面部支付 浏览:38
天元数学app为什么登录不上去 浏览:824
明日之后为什么有些服务器是四个字 浏览:104
安卓系统l1是什么意思 浏览:26