defgene_len(len, accu): ''' 基因长度计算 参数: len 区间长度(整型) accu 精确度(精确到小数点后多少位) 返回值: 二进制长度 ''' temp = len * (10 ** accu) # print(temp) i = 1 while temp > 2 : i = i + 1 temp = temp / 2 return i
defgene_decode(arr,a,b,accu): ''' 将列表转换为十进制数并映射到区间上 参数: arr 基因列表 a 区间起始点 b 区间终点 accu 精确到小数点后多少位 返回值: 十进制数 ''' #二进制转十进制 i = 0 temp = 0 for j in arr: temp = j * (2 ** i) + temp i = i + 1 #映射到区间上 res = a + (b-a)/(2**len(arr)-1)*temp res = round(res, accu) return res
defgene_init(pop, len): ''' 初始化基因序列 参数: pop 种群个数 len 个体基因长度 返回值: 二维数组 长度为种群个数 每个元素为个体基因序列 ''' return np.random.randint(2, size=(pop, len))