当前位置:首页 > 粒子群算法实现
privateintMAX_GEN;// 迭代次数 privateintscale;// 种群规模
privateintcityNum; // 城市数量,编码长度 privateintt;// 当前代数
privateint[][] distance; // 距离矩阵 privateint[][] oPopulation;// 粒子群
private ArrayList
privateint[] Pgd;// 整个粒子群经历过的的最好的解,每个粒子都能记住自己搜索到的最好解
privateintvPgd;// 最好的解的评价值 privateintbestT;// 最佳出现代数
privateint[] fitness;// 种群适应度,表示种群中各个个体的适应度 private Random random; public PSO() { } /**
* constructor of GA *
* @param n * 城市数量 * @param g * 运行代数 * @param w * 权重 **/
public PSO(intn, intg, ints, floatw) {
this.cityNum = n; this.MAX_GEN = g; this.scale = s; this.w = w; }
// 给编译器一条指令,告诉它对被批注的代码元素内部的某些警告保持静默 @SuppressWarnings(\) /**
* 初始化PSO算法类
* @param filename 数据文件名,该文件存储所有城市节点坐标数据 * @throws IOException */
privatevoid init(String filename) throws IOException { // 读取数据 int[] x; int[] y;
String strbuff;
BufferedReader data = new BufferedReader(new InputStreamReader( new FileInputStream(filename))); distance = newint[cityNum][cityNum]; x = newint[cityNum]; y = newint[cityNum]; for (inti = 0; i // 读取一行数据,数据格式1 6734 1453 strbuff = data.readLine(); // 字符分割 String[] strcol = strbuff.split(\); x[i] = Integer.valueOf(strcol[1]);// x坐标 y[i] = Integer.valueOf(strcol[2]);// y坐标 } // 计算距离矩阵 // ,针对具体问题,距离计算方法也不一样,此处用的是att48作为案例,它有48个城市,距离计算方法为伪欧氏距离,最优值为10628 for (inti = 0; i .sqrt(((x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j])) / 10.0); // 四舍五入,取整 inttij = (int) Math.round(rij); if (tij distance[i][j] = tij + 1; distance[j][i] = distance[i][j]; } else { distance[i][j] = tij; distance[j][i] = distance[i][j]; } } } distance[cityNum - 1][cityNum - 1] = 0; oPopulation = newint[scale][cityNum]; fitness = newint[scale]; Pd = newint[scale][cityNum]; vPd = newint[scale]; Pgd = newint[cityNum]; vPgd = Integer.MAX_VALUE; // nPopulation = new int[scale][cityNum]; bestT = 0; t = 0; random = new Random(System.currentTimeMillis()); } // 初始化种群,多种随机生成办法 void initGroup() { inti, j, k; for (k = 0; k oPopulation[k][0] = random.nextInt(65535) % cityNum; for (i = 1; i oPopulation[k][i] = random.nextInt(65535) % cityNum; for (j = 0; j if (oPopulation[k][i] == oPopulation[k][j]) { break; } } if (j == i) { i++; } } } } void initListV() { intra; intraA;
共分享92篇相关文档