我正在创建一个函数,允许我返回一个在整个人群中具有最佳适应度的Vector,知道健身是double
值,我的函数并不总是返回具有最大适应度的右向量矢量!!
private Vector globalbest(Vector allpop){
allpop = allPopulation;
Vector global =null;
for(int i=0;i<allPopulation.size()-1;i++)
{
double m1 =(fitness((Vector) allpop.get(i+1)));
double m2 =(fitness((Vector) allpop.get(i)));
int i1 = Double.compare(m1,m2); // if i1 is positive then the first is greater
if( i1 > 0 ){
global = null;
global = (Vector) allpop.get(i+1);
}
}
return global;
}
希望你能找到错误! 因为它真的让我感到不安和Thanx
答案 0 :(得分:1)
以下是获取最大值的替代方法。
Vector v = new Vector();
for(int i=0;i<allPopulation.size();i++)
{
double m1 =(fitness((Vector) allpop.get(i)));
v.add(m1);
}
Double max= (Double)Collections.max(v);
Vector global = (Vector) allpop.get(v.indexOf(max));
答案 1 :(得分:0)
你只是在比较allpop
中的两个相邻向量,就像这段代码所做的那样
double m1 =(fitness((Vector) allpop.get(i+1)));
double m2 =(fitness((Vector) allpop.get(i)));
这仅适用于前两个向量(即第一个迭代),之后您应该将下一个向量与前两个向量中的最佳向量进行比较
试试这个
private Vector globalbest(Vector allpop){
allpop = allPopulation;
Vector global =null;
double m1 =(fitness((Vector) allpop.get(1)));
double m2 =(fitness((Vector) allpop.get(0)));
int i1 = Double.compare(m1,m2); // if i1 is positive then the first is greater
if( i1 > 0 )
global = (Vector) allpop.get(1);
else
global = (Vector) allpop.get(0);
for(int i = 1;i<allPopulation.size()-1;i++)
{
m1 = (fitness((Vector) allpop.get(i)));
double globalfitness = (fitness((Vector) global));
int i1 = Double.compare(m1,globalfitness); //
if( i1 > 0 )
global = (Vector) allpop.get(i);
}
return global;
}
编辑根据我的评论,您应该在方法中包含向量的类型定义,如此
private Vector<Double> globalbest(Vector<Vector<Double>> allpop){...
这假设您的Vector
allPopulation是双打向量,如果没有,则将Double
更改为该类型。