人工智能遗传算法c++实现

人工智能遗传算法c++实现

#include <iostream.h>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <cmath>
#define PI 3.1415926

using namespace std;

class Software{ //软件类及其属性,即价格和运行时间
public :
float price; //价格
float time ; //时间
float adapt; //适应度范围0~1
};

double AverageRandom(double min,double max) { //产生在min与max间的随机数
int minInteger = (int)(min*10000);
int maxInteger = (int)(max*10000);
int randInteger = rand()*rand();
int diffInteger = maxInteger - minInteger;
int resultInteger = randInteger % diffInteger + minInteger;
return resultInteger/10000.0;
}

double Normal(double x,double miu,double sigma) { //概率密度函数
return 1.0/(sqrt(2*PI)*sigma) * exp(-1*(x-miu)*(x-miu)/(2*sigma*sigma));
}

double NormalRandom(double miu, double sigma,double min,double max){ //产生正态分布随机数
double x;
double dScope;
double y;
do {
x = AverageRandom(min,max);
y = Normal(x, miu, sigma);
dScope = AverageRandom(0, Normal(miu,miu,sigma));
}while( dScope > y);
return x;
}

void Init(int type, int n , vector<vector<Software> > &soft){//初始化,产生software样本组
Software temp_s;
vector<Software> temp_v;
for(int i = 0;i<n;i++){
cout<<"class "<<i+1<<endl;
for(int j=0;j<type;j++){
temp_s.price=(int)NormalRandom(0, 0.2,1,10000);
temp_s.time= (int)NormalRandom(0, 0.2,1,10);
temp_s.adapt=2/((temp_s.price/1000)+temp_s.time);
temp_v.push_back(temp_s);
cout<<j+1<<"("<<temp_s.price<<","<<temp_s.time<<","<<temp_s.adapt<<")"<<" ";
}
cout<<endl;
soft.push_back(temp_v);
temp_v.clear();
}
}

float Select(vector<vector<Software> > &soft){//选择
vector<vector<Software> > temp_soft(soft);
float share=0;
float one_share=0;
soft.clear();
for(int num=0;num<temp_soft.size();num++){
for(int type=0;type<temp_soft[num].size();type++){
share+=temp_soft[num][type].adapt;
}
}
for(num=0;num<temp_soft.size();num++){
for(int type=0;type<temp_soft[num].size();type++){
one_share+=temp_soft[num][type].adapt;
}
if(one_share>share/(2*temp_soft.size()))//如果小于两倍适应度平均值就淘汰
soft.push_back(temp_soft[num]);
one_share=0;
}
return share;
}

void Cross(int type,vector<vector<Software> > &soft){ //交叉
int dot=0;
float odds=0;
vector<Software>::iterator iter1,iter2;
for(int num=0;num<soft.size()-1;num++){
odds=rand()%100/100.0;
if(odds>0.6&&odds<0.95){//杂交率设置为0.6~0.95
dot=NormalRandom(0, 0.2,1,type);
iter1=soft[num].begin() + dot-1;
iter2=soft[num+1].begin()+dot-1;
while(iter1!=soft[num].end()){
swap(*iter1,*iter2);
iter1++;
iter2++;
}
}
}
}

void Mutation(int type,vector<vector<Software> > &soft){//变异
float odds=0;
int dot=0;
vector<Softwa

你可能喜欢

  • 遗传算法应用实例
  • 遗传算法解决TSP问题
  • 智能优化算法
  • 模拟退火算法
  • 图像匹配算法研究
  • 人工智能实验报告
  • 遗传算法matlab代码
  • 算法入门

人工智能遗传算法c++实现相关文档

最新文档

返回顶部