模擬退火算法Python實現
- 瞎BB
- 代碼
- 導入庫以及參數設置
- 目標函數
- 主函數
瞎BB
代碼
導入庫以及參數設置
import
matplotlib
.
pyplot
as
plt
import
math
import
random
T_init
=
100
# 初始最大溫度
alpha
=
0.95
# 降溫系數
T_min
=
1e
-
3
# 最小溫度,即退出循環條件
目標函數
def
obj
(
x
)
:
y
=
10
*
math
.
sin
(
5
*
x
)
+
7
*
math
.
cos
(
4
*
x
)
return
-
y
主函數
def
SA
(
T_init
,
alpha
,
T_min
)
:
T
=
T_init
x_new
=
random
.
random
(
)
*
10
#初解
x_current
=
x_new
y_current
=
float
(
'inf'
)
x_best
=
x_new
y_best
=
float
(
'inf'
)
while
T
>
T_min
:
for
i
in
range
(
100
)
:
delta_x
=
random
.
random
(
)
-
0.5
# 自變量變化后仍要求在[0,10]之間
if
0
<
(
x_new
+
delta_x
)
<
10
:
x_new
=
x_new
+
delta_x
else
:
x_new
=
x_new
-
delta_x
y_new
=
obj
(
x_new
)
if
(
y_new
<
y_current
)
:
y_current
=
y_new
x_current
=
x_new
if
(
y_new
<
y_best
)
:
y_best
=
y_new
x_best
=
x_new
else
:
if
random
.
random
(
)
<
math
.
exp
(
-
(
y_new
-
y_current
)
/
T
)
:
y_current
=
y_new
x_current
=
x_new
else
:
x_new
=
x_current
T
*=
alpha
print
(
'最優解'
,
x_best
,
obj
(
x_best
)
)
SA
(
T_init
,
alpha
,
T_min
)
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
