黄金分割法求极值点

我们先来了解什么是黄金分割算法:

    黄金分割法也称0.618算法,属于区间收缩法,首先找出包含极小点的初始搜索区间,然后黄金分割点通过对函数值的比较不断缩小搜索区间(当然要保证极小点在搜素区间),当定义域的长度缩小的一定长度时候,就可以用当前区间的端点值的平均近似代替极小值点。

注:适用范围是单谷函数(就是只有一个极大值(转化成求极小值问题)或者极小值点)

通俗点讲就是讲先给定搜索区间比如[a b],然后另x1 = a + 0.382(b - a),x2 = a + 0.618(b - a),然后把x1和x2代入到函数f(x)中比较f(x1)和f(x2)的大小,如果f(x1)>f(x2),则让a = x1,否则b = x2,然后在新的搜索区间[a b]内,重新找到x1和x2重复以上过程,直到b - a<ξ(这个是给出的最小精度),然后取a,b的平均值近似代替f(x)min。

代码实现如下:

 1 import numpy as np
 2 import matplotlib.pyplot as plt
 3 import time as tm
 4 
 5 x = np.random.rand(100)
 6 x.sort()
 7 plt.figure()
 8 plt.xlabel("t")
 9 plt.ylabel("y")
10 plt.title("0.618")
11 plt.plot(x,x*x - x + 1)
12 plt.show()
13 
14 def fun(x):
15     y = x*x - x + 1
16     return y
17 def digu(left,right,fun,dis):
18     a = left
19     b = right
20     while True:
21         c = a + 0.382*(b - a)
22         d = a + 0.618*(b - a)
23         if(abs(c-d) < dis):
24             return (c+d)/2
25         else:
26             if((fun(c) - fun(d)) > 0):
27                 a = c
28             else:
29                 b = d
30 start = tm.perf_counter()
31 print(digu(-2000,1000.,fun,0.002))
32 end = tm.perf_counter()
33 print(end-start)

运行结果:

0.4980379375572119
0.0003180240000002499

猜你喜欢

转载自www.cnblogs.com/The-Shining/p/11567128.html