解非线性方程python实现黄金分割法

1.基本概念

黄金分割法(Golden Section Method)也叫0.618法,也是一种在区间上进行迭代的数值计算方法。它与二分法都通过不断缩小搜索区间来逼近方程的解。与二分法不同的是,二分法将搜索区间均匀地切割为两半,而黄金分割法将搜索区间不等分为两部分,每次迭代后搜索区间按照黄金分割比例缩小。

2.代码实现

下面简单实现方程 f(x)=x^3-x-1=0在1到1.5之间的根。要求用四位小数计算,精确到10-2

python 复制代码
"""
@Time : 2023/11/12 0012 15:57
@Auth : yeqc
"""

# 初始区间
left = 1
right = 1.5
N = 1000  # 最大迭代次数
# 黄金分割比例
golden_ratio = (5 ** 0.5 - 1) / 2
epsilo = 10 ** (-10)


def function(x):
    return x ** 3 - x - 1


for i in range(0, N):
    center = left + (right - left) * golden_ratio
    f_left = function(left)
    f_right = function(right)
    f_center = function(center)

    if f_left * f_center < 0:
        right = center
    elif f_center * f_right < 0:
        left = center
    print(f"结果: i = {i}, x = {center}, y = {function(center)}")
    # 区间小于10-2或者函数值小于10-2 跳出循环
    if (right - left) < epsilo or abs(f_center) < epsilo:
        break
相关推荐
To_OC21 小时前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC21 小时前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
BadBadBad__AK1 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
Warson_L1 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅1 天前
海天线算法的前世今生
python·计算机视觉
韩师傅1 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L1 天前
LangGraph的MessageState and HumanMessage
python
韩师傅1 天前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L1 天前
python的类&继承
python
Warson_L1 天前
类型标注/type annotation
python