遗传算法

lr580 发表于 1年前 · 关联问题 函数2

准确度不太高,建议多遗传几次

from random import * from math import * a, b, c, d, e, l, r = [int(i) for i in input().split()] def f(x): x /= 1e7 return sin(x/a)+sin(x/b)+sin(x/c)+sin(x/d)+sin(x/e) def pick(g, fv): ran = uniform(0, 1) ac = 0 for i in range(len(fv)): ac += fv[i] if ran < ac: return g[i] return g[0] def select(g, gv): s = sum(gv) if s == 0.0: return g fv = [i/s for i in gv] return [pick(g, fv) for i in range(len(g))] def crossover(g, pc): for i in range(0, len(g), 2): if random() < pc: g[i], g[i+1] = g[i+1], g[i] return g def mutation(g, pm): for i in range(len(g)): x = 1 for j in range(32): if random() < pm: dt = x if random() < 0.5: dt *= -1 nx = dt + g[i] nf = nx / 1e7 if nf >= l and nf <= r: g[i] = nx x <<= 1 return g def ga(): pc = 0.3 pm = 0.05 g = [0 for i in range(200)] ans = -1e9 for _ in range(200): gv = [f(i) for i in g] g = select(g, gv) g = crossover(g, pc) g = mutation(g, pm) nw = max([f(i) for i in g]) ans = max(ans, nw) return ans print(max([ga() for i in range(5)]))