解非线性方程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
相关推荐
飞天小蜈蚣26 分钟前
http协议和django初识
python
路边草随风29 分钟前
langchain agent动态变更系统prompt
人工智能·python·langchain·prompt
哥本哈士奇(aspnetx)7 小时前
Streamlit + LangChain 1.0 简单实现智能问答前后端
python·大模型
我一定会有钱8 小时前
斐波纳契数列、end关键字
python
fie88898 小时前
NSCT(非下采样轮廓波变换)的分解和重建程序
算法
小鸡吃米…9 小时前
Python 列表
开发语言·python
晨晖29 小时前
单链表逆转,c语言
c语言·数据结构·算法
星依网络9 小时前
yolov5实现游戏图像识别与后续辅助功能
python·开源·游戏程序·骨骼绑定
大佐不会说日语~10 小时前
Spring AI Alibaba 的 ChatClient 工具注册与 Function Calling 实践
人工智能·spring boot·python·spring·封装·spring ai
2501_9216494910 小时前
如何获取美股实时行情:Python 量化交易指南
开发语言·后端·python·websocket·金融