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

2023-02-19 16:36:15   第一文档网     [ 字体: ] [ 阅读: ] [ 文档下载 ]

#第一文档网# 导语】以下是®第一文档网的小编为您整理的《遗传算法求函数最大值f(x)=x^2 x 从0到30》,欢迎阅读!
最大值,遗传,算法,函数
#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.dy1993.cn/dXbK.html

相关推荐