2

此代码假设减少初始游览的距离: distan(initial_tour) < distan(best) 。你能帮我吗?我已经尝试了一整天了。我需要改变我的交换方式吗? 出了点问题,模拟退火不起作用:

def prob(currentDistance,neighbourDistance,temp):

    if neighbourDistance < currentDistance:
       return 1.0

    else:
       return math.exp( (currentDistance - neighbourDistance) / temp)


def distan(solution):

    #gives the distance of solution


    listax, listay = [], []
    for i in range(len(solution)):

       listax.append(solution[i].x)
       listay.append(solution[i].y)

    dists = np.linalg.norm(np.vstack([np.diff(np.array(listax)), np.diff(np.array(listay))]), axis=0)
    cumsum_dist = np.cumsum(dists)

    return cumsum_dist[-1]


#simulated annealing

temp = 1000000

#creating initial tour

shuffle(greedys)

initial_tour=greedys


print (distan(initial_tour))

current_best = initial_tour

best = current_best

while(temp >1 ):

    #create new neighbour tour 

    new_solution= current_best 

    #Get a random positions in the neighbour tour

    tourPos1=random.randrange(0, len(dfar))
    tourPos2=random.randrange(0, len(dfar))

    tourCity1=new_solution[tourPos1]
    tourCity2=new_solution[tourPos2]

    #swapping
    new_solution[tourPos1]=tourCity2
    new_solution[tourPos2]=tourCity1

    #get distance of both current_best and its neighbour 

    currentDistance = distan(current_best)

    neighbourDistance = distan(new_solution)


    # decide if we should accept the neighbour
    # random.random() returns a number in [0,1)

    if prob(currentDistance,neighbourDistance,temp) > random.random():

        current_best = new_solution 

    # keep track of the best solution found  

    if distan(current_best) <  distan(best):

        best = current_best

    #Cool system

    temp = temp*0.99995


print(distan(best)) 
4

1 回答 1

0

你的问题在你的while循环的第一行,你写的地方

new_solution= current_best 

这样做的目的是将current_best列表的引用放入new_solution. 这意味着当你改变时new_solution,你实际上也在改变current_best,这不是你的意图。

可以通过将有问题的行替换为将列表复制到新列表中的行来解决问题,如下所示:

new_solution = list(current_best)
于 2016-10-17T01:35:46.440 回答