Python to solve the optimization problem-use the golden section method to solve the extreme point of the unimodal function

Python to solve the optimization problem-use the golden section method to solve the extreme point of the unimodal function

Algorithm principle

Insert picture description here
Insert picture description here

Algorithm Description

Insert picture description here
Insert picture description here

Algorithm implementation

def func(x):  # 目标函数
    return x**2 + x + 5


a = -100  # 初始左区间
b = 100  # 初始右区间
p = a + 0.382 * (b - a)  # 计算p
funcp = func(p)  # 计算f(p)
q = a + 0.618 * (b - a)  # 计算q
funcq = func(q)  # 计算f(q)
while (1):
    if (funcp <= funcq):  # f(p)<=f(q), 说明极小值点在(a,q)
        if (q - a <= 0.00001):  # 当区间足够小时, 则终止, 这里q一定大于a;
            print(p)  # 输出极小值点, 输出p或a, 甚至(p,a)中的任一值都可以;
            break
        else:
            b = q  # 下一个右区间b=q;
            q = p  # 根据黄金分割法的定义, 下一次计算的q等于上次的p
            funcq = funcp  # 同样, 下次计算的f(q)等于上次的f(p)
            p = a + 0.382 * (b - a)  # p要重新计算
            funcp = func(p)  # f(p)也要重新计算
    else:
        if (b - p <= 0.00001):  # 以下同理
            print(q)
            break
        else:
            a = p
            p = q
            funcp = funcq
            q = a + 0.618 * (b - a)
            funcq = func(q)

Guess you like

Origin blog.csdn.net/weixin_41754258/article/details/115044212