模拟退火算法Python实现

朴灿烈づ我的快乐病毒、 2022-01-27 06:19 463阅读 0赞

模拟退火算法Python实现

  • 瞎BB
  • 代码
    • 导入库以及参数设置
    • 目标函数
    • 主函数

瞎BB

代码

导入库以及参数设置

  1. import matplotlib.pyplot as plt
  2. import math
  3. import random
  4. T_init = 100 # 初始最大温度
  5. alpha = 0.95 # 降温系数
  6. T_min = 1e-3 # 最小温度,即退出循环条件

目标函数

  1. def obj(x):
  2. y = 10 * math.sin(5 * x) + 7 * math.cos(4 * x)
  3. return -y

主函数

  1. def SA(T_init,alpha,T_min):
  2. T = T_init
  3. x_new = random.random() * 10#初解
  4. x_current = x_new
  5. y_current = float('inf')
  6. x_best = x_new
  7. y_best = float('inf')
  8. while T > T_min:
  9. for i in range(100):
  10. delta_x = random.random() - 0.5
  11. # 自变量变化后仍要求在[0,10]之间
  12. if 0 < (x_new + delta_x) < 10:
  13. x_new = x_new + delta_x
  14. else:
  15. x_new = x_new - delta_x
  16. y_new = obj(x_new)
  17. if (y_new<y_current):
  18. y_current=y_new
  19. x_current=x_new
  20. if (y_new<y_best):
  21. y_best=y_new
  22. x_best=x_new
  23. else:
  24. if random.random() < math.exp(-(y_new - y_current) / T):
  25. y_current=y_new
  26. x_current=x_new
  27. else:
  28. x_new=x_current
  29. T *= alpha
  30. print('最优解',x_best,obj(x_best))
  31. SA(T_init,alpha,T_min)

发表评论

表情:
评论列表 (有 0 条评论,463人围观)

还没有评论,来说两句吧...

相关阅读

    相关 模拟退火算法的C#实现

    模拟退火算法的C\实现 模拟退火算法(Simulated Annealing)是一种全局优化算法,可以用于在复杂的搜索空间中找到近似最优解。它模拟固体退火过程中的原子在高温下

    相关 模拟退火算法(代码)

    在实际日常中,人们会经常遇到如下问题:在某个给定的定义域![X][]内,求函数![f(x)][f_x]对应的最优值。此处以最小值问题举例(最大值问题可以等价转化成最小值问题),