遗传算法本身是一个用来解决很复杂的系统问题时使用的算法,记一个遗传算法所能解决的最小规模的问题——求函数最大值,旨在了解遗传算法。函数f(x)如下:
f(x) = x * sin(10 * pi * x) + 1(求在[-1, 2]内的最大值)
用一个长22位的二进制串作为染色体,来表示(仅仅是表示,而不等于)x的实数值,染色体可以表示的整数的范围是0~4194304,
const int MAX = 4194304;
const int MIN = 0;
取得x所代表的实数值的函数可计算得到,在个体类(Indivaduality)里实现。同时还包括评价函数(就是题目中的f(x)),变异,交叉的方法。
#include <iostream>
#include <time.h> //产生随机数要用到time(int),以使每次产生的数不同。
#include <math.h> //sin(float)在这儿。
using namespace std;
const float pi = 3.1415926;
class Individuality {
private:
int chromosome; //染色体
public:
void set(int chromosome) { this->chromosome = chromosome; }
Individuality operator =(Individuality c) { this->chromosome = c.chromosome; return *this; }
bool operator ==(Individuality c) { return this->chromosome == c.chromosome; }
float resolve() { //通过染色体取得x的值.
return -1.0 + (float)chromosome * 3.0 / (MAX - 1);
}
float evaluate() { //f()
return resolve() * (float)sin(10*pi*resolve()) + 1.0;
}
void print() {
cout << '/t';
//以下循环是在以二进制串的形式打印染色体
for(int j = 21; j >= 0; j--)
if((1<<j) & chromosome) cout << '1';
else cout << '