解非线性方程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
相关推荐
2601_9620781915 分钟前
Python中calendar.weekday用法
python·编程技巧·calendar·日期处理·weekday
2601_9622186124 分钟前
万象生鲜系统业财一体化底层打通技术自动生成经营账单
大数据·数据库·人工智能·python·算法
2601_9669496524 分钟前
为什么量化策略需要大量历史股票数据?从回测可信度理解数据规模
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
2601_9628857230 分钟前
如何用 Python 扫描 A 股跳空缺口并统计缺口回补概率?
java·前端·python
吞下星星的少年·-·34 分钟前
The 2026 ICPC Asia East Continent Online Contest (II)(构造)
数据结构·算法
李高钢1 小时前
Python FastAPI 框架入门:从零搭建你的第一个高性能 API 服务
数据库·python·fastapi
ocean21031 小时前
2025-2026年Python面试高频知识点洞察
开发语言·python·面试·python八股文
Warson_L2 小时前
Python的OrderedDict
python
stolentime2 小时前
洛谷P10515 转圈题解
c++·算法·数学建模·贪心算法
隐擎fox2 小时前
高性能网络爬虫架构设计:基于 Python 的长连接复用与分布式会话池调度实践
分布式·python·网络协议·tcp/ip·高并发·网络爬虫、