Java实现的简单进化策略算法:ES算法的代码示例
class Point
{
int[] x;
static double xmax;
static double xmin;
static int size;
public Point()
{
x=new int[size];
init();
}
public static void set(int isize,double max,double min)
{
size=isize;
xmax=max;
xmin=min;
}
public void init()
{
for(int i=0;i<size;i++)
if(Math.random()>0.5)
x[i]=1;
else
x[i]=0;
}
public double decode()
{
double va=0.0;
for(int i=0;i<size;i++)
va=va+x[i]*Math.pow(2, size-i-1);
va=xmin+(xmax-xmin)*(va)/(Math.pow(2, size)-1.0);
return va;
}
public double getFitness()
{
double va=decode();
double y=va*Math.sin(va*10*Math.PI)+2.0;
return y;
}
public String toString()
{
String str="";
str=str+this.decode()+','+this.getFitness();
return str;
}
}
class ES
{
Point[] obj; //父代
int size; //种群规模
public ES(int isize)
{
size=isize;
obj=new Point[size];
init();
}
public void init()
{
for(int i=0;i<size;i++)
{
obj[i]=new Point();
}
}
public void mut(Point a)
{
int pos=0;
pos=(int)(Math.random()*Point.size);
a.x[pos]=(a.x[pos]+1)%2;
}
public void copy(Point a,Point b)
{
System.arraycopy(a.x, 0, b.x, 0, Point.size);
}
public int getBestPos()
{
int pos=0;
Point temp=new Point();
System.arraycopy(obj[0].x, 0, temp.x, 0, Point.size);
for(int i=1;i<size;i++)
{
if(temp.getFitness()<obj[i].getFitness())
{
System.arraycopy(obj[i].x, 0, temp.x, 0, Point.size);
pos=i;
}
}
return pos;
}
public void doAll()
{
Point temp=new Point();
for(int i=0;i<size;i++)
{
System.arraycopy(obj[i].x, 0, temp.x, 0, Point.size);
this.mut(temp);
if(temp.getFitness()>obj[i].getFitness())
System.arraycopy(temp.x, 0, obj[i].x, 0, Point.size);
}
}
}
public class TestES
{
public static void main(String[] args)
{
Point.set(22,2.0,-1.0);
ES s=new ES(40);
int n=0;
int bestPOS;
while(n<500)
{
s.doAll();
n++;
}
bestPOS=s.getBestPos();
for(int i=0;i<s.size;i++)
System.out.println(s.obj[i]);
System.out.println('Best:No.'+bestPOS);
System.out.println(s.obj[bestPOS]);
}
}
原文地址: https://www.cveoy.top/t/topic/f2pu 著作权归作者所有。请勿转载和采集!