0

我正在制作一个函数,允许我返回一个在整个人群中具有最佳适应度的向量,知道适应度是一个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

4

2 回答 2

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));
于 2013-09-03T04:18:53.927 回答
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){...

这是假设您的VectorallPopulation 是 Doubles 的向量,如果不是,则将其更改Double为类型。

于 2013-09-03T04:44:54.013 回答