Skip to content

Instantly share code, notes, and snippets.

@pourmand1376
Created January 25, 2020 22:17
Show Gist options
  • Save pourmand1376/d1e9bcb76cd3da827c88a1c1cdfa6917 to your computer and use it in GitHub Desktop.
Save pourmand1376/d1e9bcb76cd3da827c88a1c1cdfa6917 to your computer and use it in GitHub Desktop.
Minimizing Math Function with Simulated Annealing Algorithm
import math
import random
def calculateCost(x,y):
return -0.0001*((
math.fabs(
math.sin(x)*math.sin(y)*math.exp(
math.fabs(
100 - math.sqrt(x**2+y**2)/math.pi
)
)
)+1
)**0.1)
def random_generator():
range = 5
return random.random()*range-range/2
def perform_Simulated_Annealing():
max_value = 10
cuurentX=random.randint(0,max_value)
currentY = random.randint(0,max_value)
temperature = 100
iteration = 1
while 1:
current_state = calculateCost(cuurentX,currentY)
tempX = cuurentX +random_generator()
tempY = currentY+random_generator()
next_state = calculateCost(tempX,tempY)
if next_state < current_state:
currentY = tempY
cuurentX = tempX
else:
probablity =math.exp(-1*(next_state-current_state)/temperature)
if random.random() <= probablity:
currentY = tempY
cuurentX = tempX
iteration = iteration+1
temperature = temperature * 0.98
if iteration > 1000:
if current_state < next_state:
next_state = current_state
return cuurentX,currentY,next_state
answer = perform_Simulated_Annealing()
x,y,ans = answer
print ("values of x,y: ",x,y," minimized value: ",ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment