杂草算法
杂草算法IWO.cpp
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include"roundx.h"
#include"KP01.h"
#include"maxValue.h"
#include"maxValueIndex.h"
#include"minValue.h"
/* 杂草算法 */
#define sizepop 10 /* 表示种群数 */
#define maxiter 20 /* 进化次数 */
#define C 2.6 /* 背包载重*/
#define nvar 3 /* 3个变量 */
extern double v = { { 0.5, 0.4, 0.9 },
{ 0.4, 0.7, 1.1 },
{ 0.3, 0.7, 1.0 } };
extern double w = { { 0.6, 0.7, 0.8 },
{ 0.7, 0.4, 0.8 },
{ 0.5, 0.6, 0.7 } };
void main(void)
{
typedef long clock_t;
clock_t start, finish;
double duration;
start = clock();//启动计时
srand((unsigned int)time(NULL));//随机种子
srand(time(0));// 初始化随机种子
// 变量声明
int pop = { 0 }, zbest = { 0 }, newpop = {0};
int popmin = { 1, 1, 1 };
int popmax = { 3, 3, 3 };
int S = 0, Smin = 0, Smax = 5, Exponent = 2;
double sigma_initial = 0.5, sigma_final = 0.001;
double fitness = { 0 }, newfitness = 0.0;
double temp = 0.0,randk = 0.0;
double bestfitness = 0.0, sigma = 0.0, BestCost = 0.0, WorstCost=0.0,ratio=0.0;
int bestLoc = 0;
int xx = { 0 };
// 初始化种群
for (int i = 0; i < sizepop; i++)
{
for (int j = 0; j < nvar; j++)
{
randk = double(rand()) / double(RAND_MAX); //0-1随机数
temp = (popmin + randk*(popmax - popmin));
pop = roundx(temp);
}
fitness = KPO1(pop); // 适应度函数
}
// 记录一组最优值
bestfitness = maxValue(fitness);
bestLoc = maxValueIndex(fitness);
memcpy(zbest, pop, 12); // 3个整型,12个字节
// 迭代寻优
for (int iter = 0; iter < maxiter; iter++)
{
sigma = (((maxiter - iter) / (maxiter - 1)) ^ Exponent)*(sigma_initial - sigma_final) + sigma_final;
BestCost = maxValue(fitness);
WorstCost = minValue(fitness);
for (int i = 0; i < sizepop; i++)
{
ratio = (fitness - WorstCost) / (BestCost - WorstCost + 0.00000001);
S = roundx(Smin + (Smax - Smin)*ratio);
for (int j = 0; j < S; j++)
{
for (int k = 0; k < nvar; k++)
{
randk = double(rand()) / double(RAND_MAX); //0-1随机数
newpop = roundx(pop + sigma*randk);
if (newpop>popmax)
newpop = popmax;
else if (newpop < popmin)
newpop = popmin;
}
newfitness = KPO1(newpop); // 适应度函数
if (newfitness>fitness)
{
fitness = newfitness;
memcpy(pop, newpop, 12); // 3个整型,12个字节
}
if (newfitness > bestfitness)
{
bestfitness = newfitness;
memcpy(zbest, newpop, 12); // 3个整型,12个字节
}
}
}
printf("最优适应度值为: %lf\n", bestfitness); // 输出显示
}
printf("\n"); // 输出显示
// 最终的解
printf("最终的解为: \n" ); // 输出显示
for (int i = 0; i < nvar; i++)
{
if (zbest == 1)
xx = 1;
else if (zbest == 2)
xx = 1;
else if (zbest == 3)
xx = 1;
printf("%d\t %d\t %d\n", xx, xx, xx); // C0-C4输出显示
}
printf("\n"); // 输出显示
system("pause"); // 消除屏幕一闪即消失的情况
}
其中KP01.cpp、maxValue.cpp、maxValueIndex.cpp、minValue.cpp、roundx.cpp请参考教与学算法【http://halcom.cn/forum.php?mod=viewthread&tid=55572&extra=page%3D1】
bilibili视频观察代码运行效果:
https://www.bilibili.com/video/BV1rQ4y1m735/
页:
[1]