赵乐ACM

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
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)

 

posted on 2012-12-11 22:44  赵乐ACM  阅读(1359)  评论(0编辑  收藏  举报