1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
import random import math
def neighbor(last, T, t): """ returns a neighbor """ time = lambda cur: sum([cur[i] * t[i] for i in range(M)])
while True: res = [i for i in last] idx = random.randint(0, len(last) - 1) res[idx] = 1 - res[idx] if time(res) <= T: return res
def solve(T, M, t, m): value = lambda cur: sum([cur[i] * m[i] for i in range(M)])
cur_tmp = 100 tmp_fin = 0.01 ans = [0, 0, 0] val = value(ans) while cur_tmp > tmp_fin: next = neighbor(ans, T, t) next_value = value(next)
diff = next_value - val r = random.random() if next_value > val or r < math.exp(-abs(diff) / cur_tmp): ans = next val = next_value
cur_tmp = cur_tmp * 0.999
print(ans)
if __name__ == "__main__": T = 70 M = 3 t = [71, 69, 1] m = [100, 1, 2]
solve(T, M, t, m)
|