Python实现黄金分割搜索算法求解函数极值

本代码使用Python实现了黄金分割搜索算法,用于寻找函数的极值。以下代码示例展示了如何使用该算法找到函数 F(x) = 8x³ - 2x² - 7x + 3 在给定区间内的最小值。pythondef F(x): return 8x**3 - 2x**2 - 7*x + 3

def golden_section_search(a, b, h, epsilon): r = (5**0.5 - 1) / 2 c = a + (1 - r) * (b - a) d = a + r * (b - a)

while abs(b - a) > epsilon:        if F(c) < F(d):            b = d            d = c            c = a + (1 - r) * (b - a)        else:            a = c            c = d            d = a + r * (b - a)

return (a + b) / 2

设置搜索区间和精度start_point = 0step_size = 0.1convergence = 0.001

调用黄金分割搜索函数result = golden_section_search(start_point, start_point + step_size, step_size, convergence)

打印结果print('函数在区间 [', start_point, ',', start_point + step_size, '] 内的最小值接近于:', result)

代码解释:

  • F(x): 定义了目标函数 F(x).* golden_section_search(a, b, h, epsilon): 实现了黄金分割搜索算法。 * a, b: 搜索区间的左右端点. * h: 初始步长. * epsilon: 收敛精度.* start_point, step_size, convergence: 定义了搜索的起始点、步长和收敛精度。

使用方法:

  1. 将代码复制到Python环境中。2. 根据需要修改目标函数 F(x)、搜索区间 (start_point, step_size) 和收敛精度 (convergence)。3. 运行代码,程序会打印出函数在指定区间内的最小值。

注意:

  • 黄金分割搜索算法只能找到函数的局部极值。* 搜索结果的精度取决于收敛精度 epsilon 的设置。
Python实现黄金分割搜索算法求解函数极值

原文地址: https://www.cveoy.top/t/topic/Q2y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录