十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
問題
重點(diǎn)思路
爬山算法會收斂到局部最優(yōu),解決辦法是初始值在定義域上隨機(jī)取亂數(shù)100次,總不可能100次都那么倒霉。
實現(xiàn)
import numpy as np import matplotlib.pyplot as plt import math # 搜索步長 DELTA = 0.01 # 定義域x從5到8閉區(qū)間 BOUND = [5,8] # 隨機(jī)取亂數(shù)100次 GENERATION = 100 def F(x): return math.sin(x*x)+2.0*math.cos(2.0*x) def hillClimbing(x): while F(x+DELTA)>F(x) and x+DELTA<=BOUND[1] and x+DELTA>=BOUND[0]: x = x+DELTA while F(x-DELTA)>F(x) and x-DELTA<=BOUND[1] and x-DELTA>=BOUND[0]: x = x-DELTA return x,F(x) def findMax(): highest = [0,-1000] for i in range(GENERATION): x = np.random.rand()*(BOUND[1]-BOUND[0])+BOUND[0] currentValue = hillClimbing(x) print('current value is :',currentValue) if currentValue[1] > highest[1]: highest[:] = currentValue return highest [x,y] = findMax() print('highest point is x :{},y:{}'.format(x,y))