遗传算法求函数最大值f(x)=x^2 x 从0到30

发布时间:2011-01-06 10:30:39   来源:文档文库   
字号:

#include

#include

#include

#include

float f(float x)

{

return x * x;

}

void main()

{

float x[10];

float f1, f2;

int i, j;

float fmax;

int xfmax;

srand(time(NULL));

xfmax = 0;

x[0] = 15.0f;

f1 = f(x[0]);

f2 = f1 + 1.0f;

for (j = 0; fabs(f1 - f2) >= 0.0001f || j < 50; j++)

{

for (i = 0; i < 10; i++)

{

if (i != xfmax)

{

x[i] = -1;

while (!(x[i] >= 0 && x[i] <= 30))

{

x[i] = x[xfmax] + ((float)rand() / RAND_MAX * 2 - 1) * (15.0f / (j * 2 + 1));

}

}

}

xfmax = -1;

for (i = 0; i < 10; i++)

{

if (xfmax < 0 || fmax < f(x[i]))

{

fmax = f(x[i]);

xfmax = i;

}

}

f2 = f1;

f1 = fmax;

}

printf("f(%f) = %f\n", x[xfmax], fmax);

}

 8

本文来源:https://www.2haoxitong.net/k/doc/dbc85bd376a20029bd642d4f.html

《遗传算法求函数最大值f(x)=x^2 x 从0到30.doc》
将本文的Word文档下载到电脑,方便收藏和打印
推荐度:
点击下载文档

文档为doc格式