利用python构造遗传算法计算函数f(x1-x2-x3)=x1^2-x1*x2+x3的最大值以及函数f最大值时x1-x2-x3的取值x1-x2-x3∈[1,10].
方法一:
注意:需安装python第三方库:matplotlib或者numpy
import numpy as np
DNA_SIZE = 12
POP_SIZE = 200
CROSSOVER_RATE = 0.8
MUTATION_RATE = 0.005
N_GENERTATIONS = 30
X1_BOUND = [0, 10]
X2_BOUND = [0, 10]
X3_BOUND = [0, 10]
def F(x1, x2, x3):
return x1 ** 2 - x1 * x2 + x3;
def translateDNA(pop):
x1_pop = pop[:, :DNA_SIZE]
x2_pop = pop[:, DNA_SIZE:-DNA_SIZE]
x3_pop = pop[:, -DNA_SIZE:]
x1 = x1_pop.dot(2 ** np.arange(DNA_SIZE)[::-1]) / float(2 ** DNA_SIZE - 1) * (X1_BOUND[1] - X1_BOUND[0]) + X1_BOUND[
0]
x2 = x2_pop.dot(2 ** np.arange(DNA_SIZE)[::-1]) / float(2 ** DNA_SIZE - 1) * (X2_BOUND[1] - X2_BOUND[0]) + X2_BOUND[
0]
x3 = x3_pop.dot(2 ** np.arange(DNA_SIZE)[::-1]) / float(2 ** DNA_SIZE