基本上,我試圖爲多維揹包問題創建一個模擬退火的實現。我有一個問題讓系統決定是否接受一個較低值的狀態。退火進行控制這樣的功能:Java:值不更新時應更新
while (this.temp > 0)
{
System.out.println("Temperature: "+this.temp);
System.out.println("Current bag: "+bagString(currentBag)+" (Value "+problem.getValue(currentBag)+")");
next = getNext();
System.out.println("Next bag: "+bagString(next)+" (Value "+problem.getValue(next)+")");
if (acceptNext(next))
{
System.out.println("Accepted");
this.currentBag = next;
} else {
System.out.println("Not accepted");
}
this.temp -= this.delta;
}
的acceptNext()函數來決定是否接受下一個狀態,並因此被定義:
public boolean acceptNext(ArrayList<Boolean> next)
{
if (problem.getValue(next) > problem.getValue(this.currentBag))
{
return true;
} else {
int loss = (problem.getValue(this.currentBag) - problem.getValue(next));
double prob = Math.exp(loss/this.temp);
Random generator = new Random();
double selection = generator.nextDouble();
System.out.println("Prob: "+prob+", random number: "+selection);
if (selection < prob) {
return true;
}
return false;
}
}
做一些測試後,我發現在調用acceptNext()函數之前,currentBag字段被分配給下一個值。我無法在我的任何代碼中找到另一個「this.currentBag = next」。爲了完整起見,這裏是getNext()函數:
public ArrayList<Boolean> getNext()
{
Random generator = new Random();
boolean valid = false;
ArrayList<Boolean> next = new ArrayList<Boolean>();
int j;
while (!valid)
{
next = this.currentBag;
j = generator.nextInt(problem.getNumObjects());
if (next.get(j) == true)
{
next.set(j, false);
} else {
next.set(j, true);
}
if (problem.isValid(next))
{
valid = true;
}
}
return next;
}
我看不到是什麼讓這個值更新。有沒有人看到代碼中的任何東西?
感謝
本