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

遗传算法java

发布时间:2022-01-24 12:13:59

1. java实验 遗传算法

你好,我以前从csdn上下过一个源代码,不过没试过怎么用,给你参考一下:

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;

/**
* 编写者: 赖志环
* 标准遗传算法求解函数
* 编写日期: 2007-12-2
*/
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;
}

}

2. 悬赏100 java 遗传算法

加QQ 1336208558. 我发给你!

3. 求用java实现多目标遗传算法的代码

给分吧,我给你发一段。

4. 使用java来实现在智能组卷中的遗传算法(急急急)

题目好像是让你做个增强版的List ,简单的都实现了 程序架子大概是这样,排序查找什么的网络搜下 算法很多,套着每样写个方法就行了,测试就在main‘方法里写

publicclassMyList{
privateString[]arr;
privateintcount;
publicMyList(intcount){
arr=newString[count];
this.count=count;
}
publicMyList(int[]intArr){
arr=newString[intArr.length];
this.count=intArr.length;
for(inti=0;i<intArr.length;i++){
arr[i]=intArr[i]+"";
}
}

publicMyList(String[]stringArr){
arr=stringArr;
this.count=stringArr.length;
}
publicintgetLength(){
returncount;
}
//清空容器内的数组。
publicvoidclearAll(){
arr=newString[count];
}
//通过给定元素下标来删除某一元素
publicvoidremoveBySeqn(intseqn){
if(seqn>=0&&seqn<count){
arr[seqn]=null;
}
}
publicstaticvoidmain(String[]args){
MyListlist=newMyList(40);
MyListlist1=newMyList({3,2,125,56,123});
MyListlist2=newMyList({"123",""ad});
list2.removeBySeqn(0);
list1.clearAll();
}
}

5. java中有没有专门为遗传算法等智能算法设计的包呢

JGAP(Java Genetic Algorithms Package -- Java遗传算法包)

6. 求基于遗传算法的多目标优化代码 用C,C++或java实现。最好能够运行

好高深

7. 如何用Java实现遗传算法

通过遗传算法走迷宫。虽然图1和图2均成功走出迷宫,但是图1比图2的路径长的多,且复杂,遗传算法可以计算出有多少种可能性,并选择其中最简洁的作为运算结果。

示例图1:

实现代码:

importjava.util.ArrayList;

importjava.util.Collections;

importjava.util.Iterator;

importjava.util.LinkedList;

importjava.util.List;

importjava.util.Random;

/**

* 用遗传算法走迷宫

*

* @author Orisun

*

*/

publicclassGA {

intgene_len;// 基因长度

intchrom_len;// 染色体长度

intpopulation;// 种群大小

doublecross_ratio;// 交叉率

doublemuta_ratio;// 变异率

intiter_limit;// 最多进化的代数

List<boolean[]> indivials;// 存储当代种群的染色体

Labyrinth labyrinth;

intwidth;//迷宫一行有多少个格子

intheight;//迷宫有多少行

publicclassBI {

doublefitness;

boolean[] indv;

publicBI(doublef,boolean[] ind) {

fitness = f;

indv = ind;

}

publicdoublegetFitness() {

returnfitness;

}

publicboolean[] getIndv() {

returnindv;

}

}

List<BI> best_indivial;// 存储每一代中最优秀的个体

publicGA(Labyrinth labyrinth) {

this.labyrinth=labyrinth;

this.width = labyrinth.map[0].length;

this.height = labyrinth.map.length;

chrom_len =4* (width+height);

gene_len =2;

population =20;

cross_ratio =0.83;

muta_ratio =0.002;

iter_limit =300;

indivials =newArrayList<boolean[]>(population);

best_indivial =newArrayList<BI>(iter_limit);

}

publicintgetWidth() {

returnwidth;

}

publicvoidsetWidth(intwidth) {

this.width = width;

}

publicdoublegetCross_ratio() {

returncross_ratio;

}

publicList<BI> getBest_indivial() {

returnbest_indivial;

}

publicLabyrinth getLabyrinth() {

returnlabyrinth;

}

publicvoidsetLabyrinth(Labyrinth labyrinth) {

this.labyrinth = labyrinth;

}

publicvoidsetChrom_len(intchrom_len) {

this.chrom_len = chrom_len;

}

publicvoidsetPopulation(intpopulation) {

this.population = population;

}

publicvoidsetCross_ratio(doublecross_ratio) {

this.cross_ratio = cross_ratio;

}

publicvoidsetMuta_ratio(doublemuta_ratio) {

this.muta_ratio = muta_ratio;

}

publicvoidsetIter_limit(intiter_limit) {

this.iter_limit = iter_limit;

}

// 初始化种群

publicvoidinitPopulation() {

Random r =newRandom(System.currentTimeMillis());

for(inti =0; i < population; i++) {

intlen = gene_len * chrom_len;

boolean[] ind =newboolean[len];

for(intj =0; j < len; j++)

ind[j] = r.nextBoolean();

indivials.add(ind);

}

}

// 交叉

publicvoidcross(boolean[] arr1,boolean[] arr2) {

Random r =newRandom(System.currentTimeMillis());

intlength = arr1.length;

intslice =0;

do{

slice = r.nextInt(length);

}while(slice ==0);

if(slice < length /2) {

for(inti =0; i < slice; i++) {

booleantmp = arr1[i];

arr1[i] = arr2[i];

arr2[i] = tmp;

}

}else{

for(inti = slice; i < length; i++) {

booleantmp = arr1[i];

arr1[i] = arr2[i];

arr2[i] = tmp;

}

}

}

// 变异

publicvoidmutation(boolean[] indivial) {

intlength = indivial.length;

Random r =newRandom(System.currentTimeMillis());

indivial[r.nextInt(length)] ^=false;

}

// 轮盘法选择下一代,并返回当代最高的适应度值

publicdoubleselection() {

boolean[][] next_generation =newboolean[population][];// 下一代

intlength = gene_len * chrom_len;

for(inti =0; i < population; i++)

next_generation[i] =newboolean[length];

double[] cumulation =newdouble[population];

intbest_index =0;

doublemax_fitness = getFitness(indivials.get(best_index));

cumulation[0] = max_fitness;

for(inti =1; i < population; i++) {

doublefit = getFitness(indivials.get(i));

cumulation[i] = cumulation[i -1] + fit;

// 寻找当代的最优个体

if(fit > max_fitness) {

best_index = i;

max_fitness = fit;

}

}

Random rand =newRandom(System.currentTimeMillis());

for(inti =0; i < population; i++)

next_generation[i] = indivials.get(findByHalf(cumulation,

rand.nextDouble() * cumulation[population -1]));

// 把当代的最优个体及其适应度放到best_indivial中

BI bi =newBI(max_fitness, indivials.get(best_index));

// printPath(indivials.get(best_index));

//System.out.println(max_fitness);

best_indivial.add(bi);

// 新一代作为当前代

for(inti =0; i < population; i++)

indivials.set(i, next_generation[i]);

returnmax_fitness;

}

// 折半查找

publicintfindByHalf(double[] arr,doublefind) {

if(find <0|| find ==0|| find > arr[arr.length -1])

return-1;

intmin =0;

intmax = arr.length -1;

intmedium = min;

do{

if(medium == (min + max) /2)

break;

medium = (min + max) /2;

if(arr[medium] < find)

min = medium;

elseif(arr[medium] > find)

max = medium;

else

returnmedium;

}while(min < max);

returnmax;

}

// 计算适应度

publicdoublegetFitness(boolean[] indivial) {

intlength = indivial.length;

// 记录当前的位置,入口点是(1,0)

intx =1;

inty =0;

// 根据染色体中基因的指导向前走

for(inti =0; i < length; i++) {

booleanb1 = indivial[i];

booleanb2 = indivial[++i];

// 00向左走

if(b1 ==false&& b2 ==false) {

if(x >0&& labyrinth.map[y][x -1] ==true) {

x--;

}

}

// 01向右走

elseif(b1 ==false&& b2 ==true) {

if(x +1< width && labyrinth.map[y][x +1] ==true) {

x++;

}

}

// 10向上走

elseif(b1 ==true&& b2 ==false) {

if(y >0&& labyrinth.map[y -1][x] ==true) {

y--;

}

}

// 11向下走

elseif(b1 ==true&& b2 ==true) {

if(y +1< height && labyrinth.map[y +1][x] ==true) {

y++;

}

}

}

intn = Math.abs(x - labyrinth.x_end) + Math.abs(y -labyrinth.y_end) +1;

// if(n==1)

// printPath(indivial);

return1.0/ n;

}

// 运行遗传算法

publicbooleanrun() {

// 初始化种群

initPopulation();

Random rand =newRandom(System.currentTimeMillis());

booleansuccess =false;

while(iter_limit-- >0) {

// 打乱种群的顺序

Collections.shuffle(indivials);

for(inti =0; i < population -1; i +=2) {

// 交叉

if(rand.nextDouble() < cross_ratio) {

cross(indivials.get(i), indivials.get(i +1));

}

// 变异

if(rand.nextDouble() < muta_ratio) {

mutation(indivials.get(i));

}

}

// 种群更替

if(selection() ==1) {

success =true;

break;

}

}

returnsuccess;

}

// public static void main(String[] args) {

// GA ga = new GA(8, 8);

// if (!ga.run()) {

// System.out.println("没有找到走出迷宫的路径.");

// } else {

// int gen = ga.best_indivial.size();

// boolean[] indivial = ga.best_indivial.get(gen - 1).indv;

// System.out.println(ga.getPath(indivial));

// }

// }

// 根据染色体打印走法

publicString getPath(boolean[] indivial) {

intlength = indivial.length;

intx =1;

inty =0;

LinkedList<String> stack=newLinkedList<String>();

for(inti =0; i < length; i++) {

booleanb1 = indivial[i];

booleanb2 = indivial[++i];

if(b1 ==false&& b2 ==false) {

if(x >0&& labyrinth.map[y][x -1] ==true) {

x--;

if(!stack.isEmpty() && stack.peek()=="右")

stack.poll();

else

stack.push("左");

}

}elseif(b1 ==false&& b2 ==true) {

if(x +1< width && labyrinth.map[y][x +1] ==true) {

x++;

if(!stack.isEmpty() && stack.peek()=="左")

stack.poll();

else

stack.push("右");

}

}elseif(b1 ==true&& b2 ==false) {

if(y >0&& labyrinth.map[y -1][x] ==true) {

y--;

if(!stack.isEmpty() && stack.peek()=="下")

stack.poll();

else

stack.push("上");

}

}elseif(b1 ==true&& b2 ==true) {

if(y +1< height && labyrinth.map[y +1][x] ==true) {

y++;

if(!stack.isEmpty() && stack.peek()=="上")

stack.poll();

else

stack.push("下");

}

}

}

StringBuilder sb=newStringBuilder(length/4);

Iterator<String> iter=stack.descendingIterator();

while(iter.hasNext())

sb.append(iter.next());

returnsb.toString();

}

}

8. 急求 遗传算法 java程序

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;

/**
* 编写者: 赖志环
* 标准遗传算法求解函数
* 编写日期: 2007-12-2
*/
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;
}

}

9. java写的遗传算法

package baseclass;
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;

/**
* 编写者: 赖志环
* 标准遗传算法求解函数
* 编写日期: 2007-12-2
*/
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 + "个染色体"+best.str;
return str;
}

}

阅读全文

与遗传算法java相关的资料

热点内容
求知课堂python2020 浏览:260
kafka删除topic命令 浏览:759
phpsql单引号 浏览:86
英雄联盟压缩壁纸 浏览:452
办公app需要什么服务器 浏览:628
安卓服务器怎么获得 浏览:808
空调压缩机冷媒的作用 浏览:781
淘宝app是以什么为利的 浏览:657
java提取图片文字 浏览:924
我的世界手机版指令复制命令 浏览:35
java判断字符串为数字 浏览:926
androidrpc框架 浏览:490
云服务器essd和ssd 浏览:524
家用网关的加密方式 浏览:3
怎么从ppt导出pdf文件 浏览:973
换汽车空调压缩机轴承 浏览:845
平板怎么登录安卓端 浏览:197
图像拼接计算法 浏览:257
怎么打开饥荒服务器的本地文件夹 浏览:293
usb扫描枪编程 浏览:675