def annealing_optimize(domain, cost_fuc, t=10000.0, cool=0.95, step=1):
vec = [float(random.randint(domain[i][0], domain[i][1])) for i in range(len(domain))]
while t > 0.1:
i = random.randint(0, len(domain)-1)
direction = random.randint(-step, step)
new_vec = vec[:]
new_vec[i] += direction
if new_vec[i] < domain[i][0]:
new_vec[i] = domain[i][0]
elif new_vec[i] > domain[i][1]:
new_vec[i] = domain[i][1]
cost = cost_fuc(vec)
new_cost = cost_fuc(new_vec)
# ?? pow(math.e, -(new_cost-cost)/t) ???????
# ?new_cost > cost ?????t????????new_cost
# ??t????????????new_cost
# ??t???????????new_cost
if new_cost < cost or random.random() < pow(math.e, -(new_cost+cost)/t):
vec = new_vec
t *= cool
return vec, cost_fuc(vec)
评论列表
文章目录