📄 listalgorithms.cpp
字号:
// ListAlgorithms.cpp: implementation of the CListAlgorithms class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "优化算法.h"
#include "ListAlgorithms.h"
#include "math.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CListAlgorithms::CListAlgorithms()
{
m_nDim = 0;
m_bIsMax = TRUE;
m_pTargetFun = NULL;
}
CListAlgorithms::~CListAlgorithms()
{
}
BOOL CListAlgorithms::Opt(double& Result,double *pResult)
{
if(m_nDim<=0||
m_PopSize<=0||
m_pTargetFun==NULL||
pResult==NULL||
Max.GetSize()!=Min.GetSize()||
Min.GetSize()!=m_nDim||
m_SubSize<=0)
return FALSE;
if(!Init()) return FALSE;
int MaxV = MaxValue();
int MinV = MinValue();
double *pNew = new double[m_nDim+1];
if(!pNew){ Destroy();return FALSE;}
while(fabs(m_PopAry[MaxV][0]-m_PopAry[MinV][0])>0.0000001)
{
double Sum = 0;
memset(pNew,0,sizeof(double)*(m_nDim+1));
for(UINT i=0;i<m_SubSize;i++)
{
int Index = Rand(m_PopSize);
double A = Rand(0,1.0);
for(int d=1;d<m_nDim+1;d++)
pNew[d]+=m_PopAry[Index][d];
Sum += A;
}
Sum*=1.05;
if(Sum==0)Sum=1;
for(int d=1;d<m_nDim+1;d++)
{
pNew[d] /= Sum;
if(pNew[d]<Min[d-1])
pNew[d] = Min[d-1];
if(pNew[d]>Max[d-1])
pNew[d] = Max[d-1];
}
pNew[0] = Fitness(pNew+1);
if(m_bIsMax&&pNew[0]>m_PopAry[MinV][0]||!m_bIsMax&&pNew[0]<m_PopAry[MaxV][0])
{
int In = MaxV;
if(m_bIsMax)In = MinV;
memcpy(m_PopAry[In],pNew,sizeof(double)*(m_nDim+1));
}
MaxV = MaxValue();
MinV = MinValue();
}
int In = MaxV;
if(!m_bIsMax)In = MinV;
memcpy(pResult,m_PopAry[In]+1,sizeof(double)*(m_nDim));
Result = m_PopAry[In][0];
Destroy();
return TRUE;
}
BOOL CListAlgorithms::Init()
{
Destroy();
double *pData = new double[(m_nDim+1)*m_PopSize];
if(!pData) return FALSE;
for(UINT i=0;i<m_PopSize;i++,pData+=(m_nDim+1))
{
for(int d=1;d<(m_nDim+1);d++)
pData[d] = Rand(Max[d-1],Min[d-1]);
pData[0] = Fitness(pData+1);
m_PopAry.Add(pData);
}
return TRUE;
}
double CListAlgorithms::Fitness(double *x)
{
double ret = m_pTargetFun(x,m_nDim);
int S = m_lstSt.GetSize();
for(int i=0;i<S;i++)
{
St& st = m_lstSt[i];
ret+=st.pFun(x,m_nDim)*st.Alpha*(m_bIsMax?1:-1);
}
return ret;
}
void CListAlgorithms::Destroy()
{
if(m_PopAry.GetSize())
{
delete[] m_PopAry[0];
m_PopAry.RemoveAll();
}
}
int CListAlgorithms::MaxValue()
{
int ret=0;
for(UINT i=0;i<m_PopSize;i++)
if(m_PopAry[ret][0]<m_PopAry[i][0])
ret = i;
return ret;
}
int CListAlgorithms::MinValue()
{
int ret=0;
for(UINT i=0;i<m_PopSize;i++)
if(m_PopAry[ret][0]>m_PopAry[i][0])
ret = i;
return ret;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -