import random import math XMAX = 4 YMAX = 4 Tolerance = 0.000001 MarkovLength = 10000 DecayScale = 0.95 StepFactor = 0.02 Temperature = 100 AcceptPoints = 0.0 PreX = -XMAX * random.random() PreY = - YMAX * random.random() BestX = PreX; PreBestX = BestX BestY = PreY PreBestY = BestY Temperature = DecayScale * Temperature times = 1 def obj_function(x, y): return 5.0 * math.sin(x * y) + x * x + y * y j = 1 while(times < 2 or (math.fabs(obj_function(BestX, BestY) - obj_function(PreBestX, PreBestY)) > Tolerance)): j += 1 print j for i in range(MarkovLength): NextX = PreX + StepFactor * XMAX * (random.random() - 0.5) NextY = PreY + StepFactor * YMAX * (random.random() - 0.5) while not (NextX >= -XMAX and NextX <= XMAX and NextY >= -YMAX and NextY <= YMAX): NextX = PreX + StepFactor * XMAX * (random.random() - 0.5) NextY = PreY + StepFactor * YMAX * (random.random() - 0.5) if obj_function(BestX, BestY) > obj_function(NextX, NextY): PreBestX = BestX PreBestY = BestY BestX = NextX BestY = NextY if obj_function(PreX, PreY) - obj_function(NextX, NextY) > 0: PreX = NextX PreY = NextY AcceptPoints += 1 else: change = -1 * (obj_function(NextX, NextY) - obj_function(PreX, PreY)) / Temperature if math.exp(change) > random.random(): PreX = NextX PreY = NextY AcceptPoints += 1 times += 1 print BestX, BestY, obj_function(BestX, BestY)