You are on page 1of 2

二、Python 实现

首先定义需要求解的目标函数:

def func(x, y):#目标函数


result = math.pow(x - y, 2) + math.pow(x - 2, 2) + math.pow(y - 3, 4)
return result
个人设计的存储结构是 dict{:}

def get_dict(res_dict):#获取坐标:值的 dict


for i in range(4):
x = random.randint(-10, 10)
y = random.randint(-10, 10)
result = func(x, y)
loc = (x, y)
res_dict[loc] = result
return res_dict
由于在算法中对函数值排序的作用仅在于获取最大值和最小值对应的,因此只需要得到
dict 中最大和最小 value 对应的 key。因此设计两个函数返回对应的 index 或对应的 key。本
文中返回对应的 index。

def get_max():
...
return index_max

def get_min():
...
return index_min
接下来设计 5 个函数,分别用作求中间值 mean,以及 4 种探索方法计算对应的 z1, z2, z3 和
z4。此处对算法进行了一点更改,即直接比较 4 种方法的值获得一个相对最优的解。目前
测试的结果也能达到该算法执行的结果。

result_list = []#分析四种分散方法对应的 z 函数值


result_list.append(get_z1(index_max, mean, res_dict))
result_list.append(get_z2(index_max, mean, res_dict))
result_list.append(get_z3(index_max, mean, res_dict))
result_list.append(get_z4(index_max, index_min, mean, res_dict))
index = 0
flag = 0
min = result_list[0][1]#得到最小的函数值
for r in result_list:#获取最小的 z 值对应的坐标进行替换
if result_list[flag][1] <= min:
min = result_list[index][1]
index = flag
flag += 1
else:
flag += 1
z = result_list[index][1]
z_cord = tuple(result_list[index][0])#(x,y)
最后替换掉集合中的点,不断循环更新。最后满足容忍条件时结束循环。

You might also like