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

📄 jga.java

📁 实现一个函数的数值优化的遗传算法源代码
💻 JAVA
字号:
package ga;

import java.awt.Toolkit;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.Dimension;


/**无约束条件 max f(x1,x2)=21.5+x1*sin(4*pi*x1)+x2sin(20*pi*x2)

-3.0<x1<12.1

4.1<x2<5.8

1%的变异

25%交叉

旋转转轮选择


* 实现Michalewicz
*@author not attributable
*@version 1.0
 */
    public class JGA {
        bestindival bd = null;
        String[] ipop = new String[10];
        int gernation = 0;
        boolean packFrame = false;
        public JGA() {
      this.ipop = inialPops();
     }
     double calculatefitnessvalue(String str) { // str为染色体,前面18个为x1表示部分,后面15个为x2表示部分
         String str1 = str.substring(0, 18);  //(int beginIndex, int endIndex)   返回一个新字符串,它是此字符串的一个子字符串。
      // System.out.println(str1);
      String str2 = str.substring(18);   //(int beginIndex)   返回一个新的字符串,它是此字符串的一个子字符串。
      // System.out.println(str2);
      int b1 = Integer.parseInt(str1, 2);  //parseInt(String s, int radix)   使用第二个参数指定的基数,将字符串参数解析为有符号的整数。
      // System.out.println(b1);
      int b2 = Integer.parseInt(str2, 2);  //parseInt(String s)    将字符串参数作为有符号的十进制整数进行解析
      // System.out.println(b2);
      double x1 = -3.0 + b1 * (12.1 - (-3.0)) / (Math.pow(2, 18) - 1); //math.pow 是求2的18次方
      // System.out.println(x1);
      double x2 = 4.1 + b2 * (5.8 - 4.1) / (Math.pow(2, 15) - 1);//解码公式
      // System.out.println(x2);
      double fitness = 21.5 + x1 * Math.sin(4 * 3.1415926 * x1) + x2
        * Math.sin(20 * 3.1415926 * x2);
      //System.out.println("eval=f(" + x1 + "," + x2 + ")=" + fitness);
      return fitness;
     }
     String inialPop() { // 初始化10个字符串
      String res = "";
      for (int i = 0; i < 33; i++) {
       if (Math.random() > 0.5) {
        res += "0";
       } else {
        res += "1";
       }   }
      return res;
     }
     String[] inialPops() {
      String[] ipop = new String[10];
      for (int i = 0; i < 10; i++) {
       ipop[i] = inialPop();
      }
      return ipop;  }
  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 (bd == null) {
        bd = new bestindival();
        bd.fitness = evals[i];
        bd.generations = 0;
        bd.str = ipop[i];
       } else {
        if (evals[i] > bd.fitness)// 最好的记录下来
        {
         bd.fitness = evals[i];
         bd.generations = gernation;
         bd.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;
         }
        }
       }
      }  } ;
  void cross() { // 交叉率为25%,平均为25%的染色体进行交叉
      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)) % 33;//round(double a)    返回最接近参数的 long。
                                                   //round(float a)        返回最接近参数的 int。

        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;    }   }
     }
     void mutation() {
      // 1%基因变异m*pop_size 共330个基因,为了使每个基因都相投机会发生变异,需要产生[1--330]上均匀分布的
      for (int i = 0; i < 4; i++) {
          int num = (int) (Math.random() * 330 + 1);
          int chromosomeNum = (int) (num / 33) + 1; // 染色体号
          int mutationNum = num - (chromosomeNum - 1) * 33; // 基因号
          if (mutationNum == 0)
              mutationNum = 1;
          //System.out.println(num + "," + chromosomeNum + "," + mutationNum);
          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 != 33) {
                      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 != 33) {
                      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]);
      }  }

          void process() {
              for (int i = 0; i < 1000000; i++) {
                  select();
                  cross();
                  mutation();
                  gernation = i;
              }
              System.out.println("最优值" + bd.fitness + ",代数" + bd.generations);
          }
public static void main(String args[]) {
  JGA j = new JGA();
  // System.out.println(j.calculatefitnessvalue("000001010100101001101111011111110"));
  j.process();
          }
          class bestindival { // 存储最佳的
              public int generations;
              public String str;
              public double fitness;
          }
      }

    /**
     * Application entry point.
     *
     * @param args String[]
     */
  /*  public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {


                                try {
   JGA j = new JGA();
  // System.out.println(j.calculatefitnessvalue("000001010100101001101111011111110"));
  j.process();

                    UIManager.setLookAndFeel(UIManager.
                                             getSystemLookAndFeelClassName());
                } catch (Exception exception) {
                    exception.printStackTrace();
                }

                new GaApp();
            }
        }
    };
   */

⌨️ 快捷键说明

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