求函数的最大值——遗传算法

遗传算法本身是一个用来解决很复杂的系统问题时使用的算法,记一个遗传算法所能解决的最小规模的问题——求函数最大值,旨在了解遗传算法。函数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 << '

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值