# Python implements genetic algorithm to solve the optimal value of function

``````"""

( )

( )
( i i+1 )

y = 2/(x1*x1+x2*x2+100),

x1  [0,127] x2 [0,16383],
x1 7 x2 13
x1x2
"""

import random

class Population:
def __init__(self):
self.size = 1 #
self.cn_length = 20 #
self.cns = [] #
self.pc = 0.6  #
self.pm = 0.01  #
self.ans = [0,""] #

def coding(self,x1,x2):  #
return format(bin(x1)[2:], '0>7')+format(bin(x2)[2:], '0>13')

def decoding(self,s): #
return [int(s[:7],2),int(s[7:],2)]

def function(self,x1,x2): #
return 2/(x1*x1+x2*x2 + 100)

def  initialization(self): #
for i in range(self.size):
x1 = random.randint(0,127)
x2  =random.randint(0,16383)
self.cns.append(self.coding(x1,x2))

def choose(self): #
#
p = [0.0]*self.size
for i in range(self.size):
x = self.decoding(self.cns[i])
p[i] = self.function(x[0],x[1])
tmp = sum(p)
for i in range(self.size):
p[i] = p[i]/tmp
p[i] = p[i]+p[i-1] if i>0 else p[i]
#
new_cns = []
for i in range(self.size):
rand = random.random() # [0.1)
for j in range(self.size):
if p[j] >= rand:
new_cns.append(self.cns[j])
break
self.cns = new_cns
# print(f' {self.cns}')

def crossover(self): #  pc i self.size-1-i
for i in range(self.size>>1):
if random.random() < self.pc:
continue
j = self.size-1-i
a,b = self.cns[i],self.cns[j]
pos = random.randint(0,self.cn_length-1)
self.cns[i] = a[:pos] + b[pos:]
self.cns[j] = b[:pos] + a[pos:]
# print(f' {self.cns}')

def mutation(self): #  self.pm
for i in range(self.size):
if random.random() < self.pm:
continue
pos = random.randint(0,self.cn_length-1)
bit = "0" if self.cns[i][pos] == "1" else "0"
self.cns[i] = self.cns[i][:pos] + bit + self.cns[i][pos+1:]
# print(f' {self.cns}')

def get_ans(self): #
for cn in self.cns:
x = self.decoding(cn)
now = self.function(x[0],x[1])
if now > self.ans[0]:
self.ans = [now,cn]
print(self.ans)

def solving(self,size,n): #
"""
:param size:
:param n:
:return: [ ,x1,x2]
"""
self.size = size
self.initialization()

for i in range(n):
self.choose()
self.crossover()
self.mutation()
self.get_ans()
x = self.decoding(self.ans[1])
return [self.ans[0],x[0],x[1]]

test = Population()
print(test.solving(10,100))

``````