⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 gajava.txt

📁 这是一个应用遗传算法解决的函数优化问题
💻 TXT
📖 第 1 页 / 共 5 页
字号:
-import java.sql.*;
import java.util.*;
import java.math.*;
import com.microsoft.jdbc.sqlserver.SQLServerDriver;

public class GA
{
    //数据库链接设置
    String dbmsdriver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
    String dbURL = "jdbc:microsoft:sqlserver://csy:1433;DatabaseName=GA_DATA";
 public Connection con = null;
 Statement stmt = null;
    String sqlstr;

 public String[]population = new String[40]; //存放父代种群
    public String[]childrenpopulation = new String[40]; //存放子代种群
    public double[]farray = new double[40]; //存放个体的适应度
    //存放个体适应度的和,最优函数值,杂交概率
    public double sumf, bestresult, mutationprobability,precision;
    public String bestroot; //存放最优解对应的二进制串
 
    //二进制转换为十进制
    public int BiToDec(String BiString)
    {
        int i, strlen, coefficient, result;
        strlen = BiString.length();
        coefficient = 1;
        result = 0;
        for (i = strlen - 1; i >= 0; i--)
        {
            if (BiString.substring(i, i + 1).equalsIgnoreCase("1"))
                result = result + coefficient;
            coefficient = coefficient * 2;
        }
        return result;
    }
    //计算个体适应度
    public double EvaluateIndividaul(String BiString)
    {
        double result;
        Integer dec;
        dec = BiToDec(BiString);
        //result =  - 1+dec.doubleValue() * c.doubleValue() / d.doubleValue();
        result =  - 1 + dec.doubleValue() * precision;  
  result = result * Math.sin(10 * 3.14159265358979 * result) + 2.0;
        return result;
    }
    //初始化种群
    public void innitial()
    {
  //链接数据库
  try
  {
   Class.forName(dbmsdriver).newInstance();
   con = DriverManager.getConnection(dbURL, "sa", "wq");
   stmt = con.createStatement();
  }
  catch (Exception ex)
  {
   System.out.println(ex.getMessage());
  }
  
  Integer c, d;
  c = 3;//自变量区间宽度:2-(-1)=3
  d = 4194304;//2^22;
  precision = c.doubleValue() / d.doubleValue();//精度
  mutationprobability = 0.001;//设定编译概率
        String individaul = "";
        Random ran = new Random();
        for (int i = 0; i < 40; i++)
        {
            for (int j = 0; j < 22; j++)
            {
                if (ran.nextBoolean())
                    individaul += '1';
                else
                    individaul += '0';
            }
            population[i] = individaul;
            individaul = "";
        }
    }
    //计算种群适应度
    public void Evaluate()
    {
        sumf = 0;
        bestresult = 0;
        for (int i = 0; i < 40; i++)
        {
            farray[i] = EvaluateIndividaul(population[i]);
            sumf = sumf + farray[i];
            //记录最优个体
   if (farray[i] >= bestresult)
            {
                bestresult = farray[i];
                bestroot = population[i];
            }
        }
    }
    //选择操作,使用轮盘赌选择法
    public void Select()
    {
        double SelectProbability, Pi;
        for (int i = 0; i < 40; i++)
        {
            Random ran = new Random();
            SelectProbability = ran.nextDouble(); //选择概率
            Pi = 0;
            for (int j = 0; j < 40; j++)
            {
                Pi = Pi + farray[j] / sumf;
                if (SelectProbability < Pi)
                {
                    childrenpopulation[i] = population[j];
                    break;
                }
            }
        }
    }
    //杂交操作
    public void Crossover()
    {
        int i, crossoverpos;
        String parent1, parent2;
        String temp1, temp2;

        for (i = 0; i < 40; i = i + 2)
        {
            parent1 = childrenpopulation[i];
            parent2 = childrenpopulation[i + 1];

            Random ran = new Random();
            crossoverpos = ran.nextInt(22);
            if (crossoverpos == 0 || crossoverpos == 22)
                ;
            else
            {
                temp1 = parent1.substring(0, crossoverpos) 
      + parent2.substring(crossoverpos);
                temp2 = parent2.substring(0, crossoverpos) 
      + parent1.substring(crossoverpos);
                childrenpopulation[i] = temp1;
                childrenpopulation[i + 1] = temp2;
            }
        }
    }
    //变异操作
    public void Mutation()
    {
        int mutationpos;
        for (int i = 0; i < 40; i++)
        {
            Random ran = new Random();
            if (mutationprobability > ran.nextDouble())
            {
                mutationpos = ran.nextInt(22);
                if (mutationpos != 0)
                {
                    if (childrenpopulation[i].substring(mutationpos,mutationpos + 1).equalsIgnoreCase("1"))
                        childrenpopulation[i] = childrenpopulation[i].substring(0, mutationpos) 
       + "0" +childrenpopulation[i].substring(mutationpos + 1);
                    else
                        childrenpopulation[i] = childrenpopulation[i].substring(0, mutationpos) 
       + "1" +childrenpopulation[i].substring(mutationpos + 1);
                }
            }
        }
    }

 //把个体写入数据库,以分析个体的变化
 public void SavePopulation(int k, int j)
 { 
  try
  {
    for (int i = 0; i < 40; i++)
   {
    sqlstr ="INSERT INTO [POPULATION]([SelectMethod],[TestCount],[GENERATION], [INDIVIDAUL_INDEX],[BISTR])" 
      + " values('roulette wheel selection'," 
      + Integer.toString(k) + "," 
      + Integer.toString(j) + "," 
      + Integer.toString(i) + "," 
      + "'" + population[i] + "')";
                 stmt.executeUpdate(sqlstr);
             }
  }
     catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        }
 }
 
 //把最优解写入数据库
 public void SaveBestValue(int k,int j)
 {
  double dbestroot;
  Integer a;
  a = BiToDec(bestroot);
  //dbestroot =  - 1+a.doubleValue() * b.doubleValue() / c.doubleValue();
  dbestroot =  - 1+a.doubleValue() * precision;
  try
  {
   sqlstr =
    "INSERT INTO [TESTDATA]([SelectMethod],[TestCount],[GenerationCount], [MaxValue],[BestRoot])" 
    + " values('roulette wheel selection'," 
    + Integer.toString(k) + ',' 
    + Integer.toString(j) + ',' 
    + Double.toString(bestresult) + ','
    + Double.toString(dbestroot) + ")";
   stmt.executeUpdate(sqlstr); 
  }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        }
 }
 
 public void ClostDBConn()
 {
  try
  {
   con.close();
  }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        } 
 
 }

 //主函数
    public static void main(String[]args)
    {
  //实验次数
  for (int k = 0; k < 1000; k++)
  {
   GA gatest = new GA();
   gatest.innitial();
   //每次实验的最大代数
   for (int j = 0; j < 50; j++)
   {
    gatest.Evaluate();
    gatest.Select();
    gatest.Crossover();
    gatest.Mutation();

    gatest.SavePopulation(k,j);//保存群体信息

    //把产生的子代付给父代,为下一轮准备
    for (int i = 0; i < 40; i++)
    {
     gatest.population[i] = gatest.childrenpopulation[i];
    }

    gatest.SaveBestValue(k,j);//保存最优解信息

    //显示进度
    System.out.print(k);
    System.out.print("次实验|");
    System.out.print(j);
    System.out.println("代");
   } //每次实验代数
   gatest.ClostDBConn();//关闭数据库链接
  } //实验次数  
    } //main
    //耗时38分9秒
}













我用java写的遗传算法的严重问题,程序没错,但不知道为什么结果总和预想的不同,实在是困惑,请帮忙啊!!!! 
发表于: 2007-2-6 下午8:33         回复  
 
源程序如下:

import java.io.IOException;
import java.io.File;
import java.io.FileReader;
import java.io.*;

public class GeneticAlgorithm {

/*
         A. M:群体大小。一般取为20~100;
         B. T:遗传运算终止进化代数。一般取为100~500;
         C. Pc:交叉概率。一般取为0.4~0.99;
         D. Pm:变异概率。一般取为0.0001~0.1。
     */
/* Change any of these parameters to match your needs */

static int POPSIZE = 5; /* population size */
static int MAXGENS = 5; /* max. number of generations */
static int NVARS = 3; /* no. of problem variables */
static float PXOVER = 0.8f; /* probability of crossover */
static float PMUTATION = 0.3f; /* probability of mutation */

int E = 6; 
int T = 120; 
int generation; /* current generation no. */
int cur_best; /* best individual */
//FILE * galog; /* an output file */


    BufferedReader infile;
    FileReader in;
    BufferedWriter outfile;
    FileWriter out;

    Genotype population[];
    Genotype newpopulation[];
    
int p[][][] = { { {0, 1, 1}, {0, 0, 0}, {0, 1, 1}, {0, 0, 0}
}, { {1, 0, 0}, {0, 0, 0}, {1, 0, 0}, {0, 0, 0}
}, { {0, 0, 0}, {0, 1, 1}, {0, 0, 0}, {0, 1, 1}
}, { {0, 0, 0}, {1, 0, 0}, {0, 0, 0}, {1, 0, 0}
}
};

double a[][][] = { { {10, 1, 1}, {10, 2, 4}, {1, 2.3, 1}, {3, 5, 1}
}, { {1, 3, 0.8}, {2, 3, 1.5}, {1, 1, 2}, {2, 0.7, 4}
}, { {2.5, 1.2, 3.4}, {10, 1, 1}, {1, 0.8, 13}, {1.9, 1, 1}
}, { {0.4, 3, 2.3}, {1, 2.1, 4}, {3.2, 1, 0.5}, {1, 1.4, 1.6}
}
};

double u[][][] = { { {2, 1, 1}, {3, 2, 4}, {1, 2.3, 1}, {3, 2, 1}
}, { {1, 3, 0.8}, {2, 3, 1.5}, {1, 1, 0.9}, {2, 0.7, 4}
}, { {0.7, 1.2, 3.4}, {0.5, 1, 1}, {1, 0.8, 0.9}, {1.9, 1, 1}
}, { {0.4, 3, 2.3}, {1, 2.1, 4}, {0.4, 1, 0.3}, {1, 1.4, 0.8}
}
};

double s[][][] = { { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
}, { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
}, { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
}, { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
}, { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
}
};

    GeneticAlgorithm() {
      
        population = new Genotype[POPSIZE + 1]; /* population */
        newpopulation = new Genotype[POPSIZE + 1]; /* new population; */
for (int i = 0; i <= POPSIZE; i++) {
            population[i] = new Genotype();
            newpopulation[i] = new Genotype();
}
}

class Genotype /* genotype (GT), a member of the population */
{
double gene[];
double fitness;
double upper[];
double lower[];
double cfitness;
double rfitness;
        Genotype() {
            gene = new double[NVARS]; /* a string of variables */
            fitness = 0; /* GT's fitness */
            upper = new double[NVARS]; 
            lower = new double[NVARS]; /* GT's variables lower bound */
            rfitness = 0; 
            cfitness = 0; 
}
}
/***************************************************************/
/* 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() {
        String str;
        String parts[];
try {
            in = new FileReader("gadata.txt");
            infile = new BufferedReader(in);
int i, j;
double lbound, ubound;
while ((str = infile.readLine()) != null) {
                parts = str.split(" ");
for (i = 0; i < NVARS; i++) {
                    lbound = Double.parseDouble(parts[0]);
                    ubound = Double.parseDouble(parts[1]);

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],

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -