Created
June 30, 2015 12:42
-
-
Save cocomoff/2a2418377e15970db792 to your computer and use it in GitHub Desktop.
焼きなまし法(http://d.hatena.ne.jp/jetbead/20120623/1340419446) をpythonへ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# author: @taki__taki__ | |
# date: 30/06/2015 | |
from random import random | |
from math import exp | |
class SA(object): | |
# function | |
def f(self, x): | |
return -3*x*x*x*x + 3*x*x*x + 10*x*x - 10*x + 15.0 | |
# initializing parameters | |
def __init__(self, init_x, t, r): | |
self.x = init_x | |
self.z = init_x | |
self.best = self.f(self.z) | |
self.T = t | |
self.R = r | |
# return answer | |
def get_best(self): | |
return self.z | |
# updating functions | |
def get_random_neighbor(self, xx): | |
return xx + 0.01 if random() < 0.5 else xx - 0.01 | |
def next_T(self, t): | |
return t * 0.995 | |
def next_R(self, r): | |
return self.R | |
# search | |
def calc(self): | |
while self.T > 1.0: | |
for r in xrange(self.R): | |
y = self.get_random_neighbor(self.x) | |
fx = self.f(self.x) | |
delta = fx - self.f(y) | |
if delta < 0.0 or exp(-delta / self.T) > random(): | |
self.x = y | |
if fx > self.best: | |
self.best = fx | |
self.z = self.x | |
# output search process | |
print( self.x ) | |
print("#{0}".format(self.best)) | |
self.T = self.next_T(self.T) | |
self.R = self.next_R(self.R) | |
return 0 | |
if __name__ == '__main__': | |
sa = SA(0.001, 100, 1000) | |
sa.calc() | |
print( sa.get_best() ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment