Mountain climbing algorithm to find the function value
Description of algorithm ideas :
There's no time ... Let's sleep on it
import random, math
import numpy as np
def f(x,y):
def mul(x,y):
return math.exp(-x**2-y**2)
return mul(x,y)+2*mul(x-5,y-5)
def get_para(x,y,x_delta,y_delta):
para = [[x,y],[x-x_delta, y],[x+x_delta, y],[x,y+y_delta],[x,y-y_delta],
[x-x_delta, y-y_delta],[x+x_delta, y-y_delta],[x-x_delta,y+y_delta],[x-x_delta,y-y_delta],
[x-x_delta, y+y_delta],[x+x_delta, y+y_delta],[x+x_delta,y+y_delta],[x+x_delta,y-y_delta]]
# print('para',para)
rs = []
for xy in para:
rs.append(f(xy[0],xy[1]))
# print('rssrsrs',rs)
best_index = rs.index(max(rs))
# print('best_index',best_index)
# print('best_para',para[best_index])
return para[best_index]
if __name__ == '__main__':
print(f(20,2))
x_delta=0.1
y_delta=0.1
x,y = 1,1
xy_best = get_para(x,y,0.5,0.5)
print(111,xy_best)
rs_best = f(xy_best[0],xy_best[1])
# print(rs_best)
for i in range(10000):
new_xy_best = get_para(xy_best[0],xy_best[1],x_delta,y_delta)
# print(222,new_xy_best)
# print(new_xy_best)
if rs_best == f(new_xy_best[0],new_xy_best[1]):
x_delta += 0.01
y_delta += 0.01
elif rs_best < f(new_xy_best[0],new_xy_best[1]):
x_delta = 0.1
y_delta = 0.1
# print(11,rs_best, f(new_xy_best[0],new_xy_best[1]))
xy_best = new_xy_best
rs_best = f(new_xy_best[0],new_xy_best[1])
print(i,xy_best, rs_best)
print(xy_best, f(5,5))
# print(rs_best,f(xy_best[0],xy_best[1]))
Running results :
0 [0.4, 0.4] 0.7261490370736908
1 [0.30000000000000004, 0.30000000000000004] 0.835270211411272
2 [0.20000000000000004, 0.20000000000000004] 0.9231163463866358
3 [0.10000000000000003, 0.10000000000000003] 0.9801986733067553
4 [2.7755575615628914e-17, 2.7755575615628914e-17] 1.0
437 [4.41999999999995, 4.41999999999995] 1.0205555955908896
438 [4.51999999999995, 4.51999999999995] 1.261557641094735
439 [4.6199999999999495, 4.6199999999999495] 1.4983240456498703
440 [4.719999999999949, 4.719999999999949] 1.7097500334492415
441 [4.819999999999949, 4.819999999999949] 1.8745097912252862
442 [4.919999999999948, 4.919999999999948] 1.9745631431805484
443 [5.019999999999948, 5.019999999999948] 1.9984006398293757
[5.019999999999948, 5.019999999999948] 2.0
Reference resources :
Mountain climbing algorithm _csuzhucong The blog of -CSDN Blog _ Mountain climbing algorithm