Advertisement
Guest User

Untitled

a guest
May 25th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. import random
  2. import math
  3.  
  4.  
  5. def d1(a, b): return abs(a - b) + (1 + b - a)*((a == 10 and b == 1) or (a == 1 and b == 10))
  6.  
  7.  
  8. def d2(a, b):
  9. if (a == 1 and b == 2) or (a == 9 and b == 10): return 1
  10. else:
  11. return (a != b)*(a**3 + b**3 - a**2*b - b**2*a + 4*a**2 - 4*b**2 + 4*a + 4*b) if b <= a else d2(b, a)
  12.  
  13.  
  14. def E(perm, d): return sum(d(perm[i], perm[i+1]) for i in range(9))
  15.  
  16.  
  17. def nowe_s(S):
  18. i = random.randint(1, 9)
  19. j = random.randint(0, i - 1)
  20. S[i], S[j] = S[j], S[i]
  21. return S
  22.  
  23.  
  24. def accept(T, S, S1, d):
  25. rand = random.random()
  26. return E(S1, d) - E(S, d) < 0 or rand < math.e**((E(S, d) - E(S1, d))/T)
  27.  
  28.  
  29. def nowe_t(t, T):
  30. return T/(1+math.log(t+1))
  31.  
  32.  
  33. def annealing(M, L, T0, d):
  34. S = list(range(1, 11))
  35. random.shuffle(S) # losowy start
  36. t, accsol, T = 0, 0, T0
  37. while accsol < L:
  38. for x in range(0, M):
  39. S1 = nowe_s(S)
  40. if accept(T, S, S1, d):
  41. S = S1
  42. accsol += 1
  43. T = nowe_t(t, T)
  44. t += 1
  45. return S
  46.  
  47.  
  48. pom = annealing(10, 3, 100, d1)
  49. while E(pom , d1) > 15:
  50. pom = annealing(10, 3, 100, d1)
  51. print(pom, E(pom, d1))
  52. pom = annealing(10, 3, 100, d2)
  53. print(pom, E(pom, d2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement