焼きなまし法
🔥 Vibe プロンプト
「50のランダム都市で焼きなまし法によりTSPを解決。ルート最適化のアニメーションを表示。」
import random, math
def simulated_annealing(cities, initial_temp=1000, cooling_rate=0.995, stop_temp=0.01):
n = len(cities)
def dist(i, j): return math.sqrt((cities[i][0]-cities[j][0])**2 + (cities[i][1]-cities[j][1])**2)
def total_dist(route): return sum(dist(route[i], route[(i+1)%n]) for i in range(n))
current = list(range(n))
random.shuffle(current)
current_dist = total_dist(current)
best, best_dist = current[:], current_dist
temp = initial_temp
while temp > stop_temp:
i, j = random.sample(range(n), 2)
new = current[:]
new[i], new[j] = new[j], new[i]
new_dist = total_dist(new)
delta = new_dist - current_dist
if delta < 0 or random.random() < math.exp(-delta/temp):
current, current_dist = new, new_dist
if current_dist < best_dist:
best, best_dist = current[:], current_dist
temp *= cooling_rate
return best, best_dist
cities = [(random.random()*100, random.random()*100) for _ in range(50)]
route, dist = simulated_annealing(cities)
print(f"最適距離: {dist:.2f}")
章のまとめ
- コアコンセプトと原理を理解
- 実装方法とテクニックを習得
- 一般的な問題と解決策に精通
- 実際のプロジェクトに適用可能
さらに読む
- 公式ドキュメントとAPIリファレンス
- GitHubのオープンソース例
- 技術書とオンラインコース
- コミュニティディスカッションと技術ブログ
実装例
基本例
# 完全な実装例を提供します
手順
- セットアップ: 開発環境の設定
- データ: 必要なデータの準備
- 実装: コア機能の構築
- テスト: 動作確認
- 最適化: パフォーマンスの向上
よくあるエラー
| エラー種別 | 原因 | 解決方法 | |-----------|------|---------| | コンパイル | 構文 | コードの構文を確認 | | 実行時 | 環境 | 依存パッケージの確認 | | 論理 | アルゴリズム | ステップごとのデバッグ | | パフォーマンス | 効率 | プロファイラーの使用 |
コード例
import sys
def main():
print("Hello, World!")
if __name__ == "__main__":
main()
参考資料
- 公式ドキュメント
- APIリファレンス
- オープンソース例
- コミュニティディスカッション